﻿/* $RCSFile: Crm2Crm.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Crm2Crm/Crm2Crm.ascx.cs $
 * $log$
 * Revision 55 2010/10/03 22:26:39  christian.surieux
 *   Added test to avoid create on entities which can't be created
 * Revision 27 2010/10/02 14:03:22  christian.surieux
 *   Corrected a bug in Crm2Crm concerning RetrieveLookup
 * Revision 20 2010/08/09 10:51:19  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:46  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Web.UI.HtmlControls;
using System.IO;
using System.ComponentModel;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using CrmSdk;

using Telerik.Web.UI;
using Telerik.Web.UI.Upload;

using Trace2    =   System.Diagnostics.Trace;


namespace AddonNice.PageModules.Crm2Crm
{

	#region Local TraceSwitch 
	public class Crm2CrmTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("Crm2CrmTrace","Special Trace Switch for Crm2Crm Trace");
	}
	#endregion Local TraceSwitch 

    public class ST2C
    {
        public const string CRMVersion              =   "CRM2CRM_CRM_VERSION";
        public const string Organization            =   "CRM2CRM_ORGANIZATION";
        public const string DiscoServer             =   "CRM2CRM_DISCOSERVER";
        public const string DiscoPort               =   "CRM2CRM_DISCOPORT";
        public const string ServerUrl               =   "CRM2CRM_CRM3SERVERURL";
        public const string Login                   =   "CRM2CRM_SOURCE_ADMINLOGIN";
        public const string Domain                  =   "CRM2CRM_SOURCE_ADMINDOMAIN";
        
        public const string SaveExecSummary         =   "CRM2CRM_SOURCE_SAVEEXECSUMMARY";
        public const string UseSiteDefault          =   "CRM2CRM_SOURCE_USESITEDEFAULT";
        public const string DocumentsFolder         =   "CRM2CRM_SOURCE_SAVEFOLDER";

        public const string CopyAllDates            =   "CRM2CRM_SOURCE_COPYALLDATES";
        public const string FirstDuplicate          =   "CRM2CRM_ONLY1DUP";
        public const string DefaultCheckDup         =   "CRM2CRM_SOURCE_DEFAULTCHECKDUP";
        public const string UpdateExisting          =   "CRM2CRM_SOURCE_UPDATEEXISTING";
        public const string Customers               =   "CRM2CRM_CUSTOMERS";
        public const string CustomerRelations       =   "CRM2CRM_CUSTOMERSRELATIONS";
        public const string Products                =   "CRM2CRM_PRODUCTS";
        public const string Opportunities           =   "CRM2CRM_OPPORTUNITIES";
        public const string Quotes                  =   "CRM2CRM_QUOTES";
        public const string Orders                  =   "CRM2CRM_ORDERS";
        public const string Invoices                =   "CRM2CRM_INVOICES";
        public const string Activities              =   "CRM2CRM_ACTIVITIES";
        public const string Lists                   =   "CRM2CRM_LISTS";
        public const string Campaigns               =   "CRM2CRM_CAMPAIGNS";
        public const string Contracts               =   "CRM2CRM_CONTRACTS";
        public const string Service                 =   "CRM2CRM_SERVICE";
        public const string Calendars               =   "CRM2CRM_CALENDAR";

        public const string CustomersDups           =   "CRM2CRM_CUSTOMERSDUPS";
        public const string CustomerRelationsDups   =   "CRM2CRM_CUSTOMERSRELATIONSDUPS";
        public const string ProductsDups            =   "CRM2CRM_PRODUCTSDUPS";
        public const string OpportunitiesDups       =   "CRM2CRM_OPPORTUNITIESDUPS";
        public const string QuotesDups              =   "CRM2CRM_QUOTESDUPS";
        public const string OrdersDups              =   "CRM2CRM_ORDERSDUPS";
        public const string InvoicesDups            =   "CRM2CRM_INVOICESDUPS";
        public const string ActivitiesDups          =   "CRM2CRM_ACTIVITIESDUPS";
        public const string ListsDups               =   "CRM2CRM_LISTSDUPS";
        public const string CampaignsDups           =   "CRM2CRM_CAMPAIGNSDUPS";
        public const string ContractsDups           =   "CRM2CRM_CONTRACTSDUPS";
        public const string ServiceDups             =   "CRM2CRM_SERVICEDUPS";
    }
    
    /// <summary>
    /// Initializer for announcements 
    /// </summary>
    public class Crm2CrmSI : PortalCRMModuleControlSI
    {
        public Crm2CrmSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Crm2CrmSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Crm2CrmSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }

        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Crm2CrmSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                   =   pm.ExtendedResourcesGroup;
            const string extgrp1            =   "CRM2CRM_FIELDS";
			
            ArrayList arlv                  =   new ArrayList();
            arlv.Add(new ListItem("Version 3","3"));
            arlv.Add(new ListItem("Version 4","4"));
            
            SettingItemSpecial Field_id	    =	new SettingItemSpecial(ST2C.CRMVersion,new CustomListDataType(arlv,"Text","Value"));
			Field_id.Order			        =	10;
            Field_id.Value			        =	"4";
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"CRM Version";
            Field_id.EnglishName		    =	"CRM Version";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Organization,new StringDataType());
			Field_id.Order			        =	15;
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Source Orgzanization for CRM v4";
            Field_id.EnglishName		    =	"Source CRMv 4 Orgzanization";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.DiscoServer,new StringDataType());
			Field_id.Order			        =	20;
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Source Disovery server for CRM v4";
            Field_id.EnglishName		    =	"Source CRM v4 Discovery Server";
			bSettings.AddSetting(Field_id);

            IntegerDataType idt             =   new IntegerDataType();
            idt.DecimalDigits               =   0;
            Field_id	                    =	new SettingItemSpecial(ST2C.DiscoPort,idt);
			Field_id.Order			        =	25;
			Field_id.Value                  =	"80";
            Field_id.MinValue               =   0;
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Source Disovery server Port number";
            Field_id.EnglishName		    =	"Discovery Server Port";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.ServerUrl,new StringDataType());
			Field_id.Order			        =	30;
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Source server URL for CRM v3";
            Field_id.EnglishName		    =	"Source CRM v3 Server URL";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Login,new StringDataType());
			Field_id.Order			        =	35;
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"CRM Administrator login";
            Field_id.EnglishName		    =	"Administrator login";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Domain,new StringDataType());
			Field_id.Order			        =	38;
			Field_id.ExtendedGroupName      =   extgrp;
			Field_id.Description		    =	"Source windows Domain";
            Field_id.EnglishName		    =	"Source Domain";
			bSettings.AddSetting(Field_id);

            SettingItemSpecial SaveExecSummary =   new SettingItemSpecial(ST2C.SaveExecSummary,new BooleanDataType());
            SaveExecSummary.Value              =   StStr.strTrue;
            SaveExecSummary.Order              =   39;
            SaveExecSummary.ExtendedGroupName  =   extgrp;
            SaveExecSummary.EnglishName        =   "Save execution summary";
            SaveExecSummary.Description        =   "When checked a summary for each execution wil be save in the selected folder";
            bSettings.AddSetting(SaveExecSummary);

            SettingItemSpecial UseDefaultPath =   new SettingItemSpecial(ST2C.UseSiteDefault,new BooleanDataType());
            UseDefaultPath.Value              =   StStr.strTrue;
            UseDefaultPath.Order              =   40;
            UseDefaultPath.ExtendedGroupName  =   extgrp;
            UseDefaultPath.EnglishName        =   "Save in Default Document Portal Path";
            UseDefaultPath.Description        =   "Take the path set in Site Settings as default Document repository";
            bSettings.AddSetting(UseDefaultPath);

            SettingItemSpecial StDocumentsFolder =   new SettingItemSpecial(ST2C.DocumentsFolder,new PortalUrlDataType());
            StDocumentsFolder.Required           =   false;
			StDocumentsFolder.Order              =   41;
            StDocumentsFolder.Value              =   StStr.DocumentsBaseFolderName;
			StDocumentsFolder.ExtendedGroupName  =   extgrp;
            StDocumentsFolder.EnglishName        =	"Dedicated save folder";
			StDocumentsFolder.Description        =	"Set the folder where summary will be saved";
			bSettings.AddSetting(StDocumentsFolder);           

            Field_id	                    =	new SettingItemSpecial(ST2C.CopyAllDates,new BooleanDataType());
			Field_id.Order			        =	42;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            Field_id.Description		    =	"When checked, copy entities whatever are creation dates, else entities created copy from input start date";
            Field_id.EnglishName		    =	"Copy all dates";
			bSettings.AddSetting(Field_id);

            
            Field_id	                    =	new SettingItemSpecial(ST2C.DefaultCheckDup,new BooleanDataType());
			Field_id.Order			        =	43;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            Field_id.Description		    =	"Check for duplicates on any entity where it is not factually specified";
            Field_id.EnglishName		    =	"Default duplicate check";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.FirstDuplicate,new BooleanDataType());
			Field_id.Order			        =	44;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            Field_id.Description		    =	"Select first duplicate when several else select none";
            Field_id.EnglishName		    =	"Select first duplicate when several";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.UpdateExisting,new BooleanDataType());
			Field_id.Order			        =	45;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            Field_id.Description		    =	"When checked, perform an update on duplicate items";
            Field_id.EnglishName		    =	"Update duplicate items";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.Customers,new BooleanDataType());
			Field_id.Order			        =	50;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            Field_id.Description		    =	"Should we copy Customers";
            Field_id.EnglishName		    =	"Duplicate Customers";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.CustomersDups,new BooleanDataType());
			Field_id.Order			        =	55;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.Description		    =	"Should we check duplicate customers ";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.CustomerRelations,new BooleanDataType());
			Field_id.Order			        =	60;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.Description		    =	"Should we copy Relationsship";
            Field_id.EnglishName		    =	"Duplicate Relations";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.CustomerRelationsDups,new BooleanDataType());
			Field_id.Order			        =	65;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate relations";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Products,new BooleanDataType());
			Field_id.Order			        =	70;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy Relationsship";
            Field_id.EnglishName		    =	"Duplicate Relations";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.ProductsDups,new BooleanDataType());
			Field_id.Order			        =	75;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate products";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Opportunities,new BooleanDataType());
			Field_id.Order			        =	80;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy opportunites";
            Field_id.EnglishName		    =	"Duplicate Relations";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.OpportunitiesDups,new BooleanDataType());
			Field_id.Order			        =	85;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate opportunites";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Quotes,new BooleanDataType());
			Field_id.Order			        =	90;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy quotes";
            Field_id.EnglishName		    =	"Duplicate Quotes";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.QuotesDups,new BooleanDataType());
			Field_id.Order			        =	95;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate quotes";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Orders,new BooleanDataType());
			Field_id.Order			        =	100;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy orders";
            Field_id.EnglishName		    =	"Duplicate Orders";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.OrdersDups,new BooleanDataType());
			Field_id.Order			        =	105;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate orders";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Invoices,new BooleanDataType());
			Field_id.Order			        =	110;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy invoices";
            Field_id.EnglishName		    =	"Duplicate Invoices";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.InvoicesDups,new BooleanDataType());
			Field_id.Order			        =	115;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate invoices";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Activities,new BooleanDataType());
			Field_id.Order			        =	120;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy Activities";
            Field_id.EnglishName		    =	"Duplicate Activities";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.ActivitiesDups,new BooleanDataType());
			Field_id.Order			        =	125;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate Activities";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Lists,new BooleanDataType());
			Field_id.Order			        =	130;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy marketing Lists";
            Field_id.EnglishName		    =	"Duplicate Lists";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.ListsDups,new BooleanDataType());
			Field_id.Order			        =	135;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate Lists";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Campaigns,new BooleanDataType());
			Field_id.Order			        =	140;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy marketing Campaigns";
            Field_id.EnglishName		    =	"Duplicate Campaigns";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.CampaignsDups,new BooleanDataType());
			Field_id.Order			        =	145;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate Campaigns";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Contracts,new BooleanDataType());
			Field_id.Order			        =	150;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy marketing Contracts";
            Field_id.EnglishName		    =	"Duplicate Contracts";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.ContractsDups,new BooleanDataType());
			Field_id.Order			        =	155;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate Contracts";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.Calendars,new BooleanDataType());
			Field_id.Order			        =	158;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy Calendars";
            Field_id.EnglishName		    =	"Copy Calendars";
			bSettings.AddSetting(Field_id);


            Field_id	                    =	new SettingItemSpecial(ST2C.Service,new BooleanDataType());
			Field_id.Order			        =	160;
            Field_id.Value			        =	StStr.strTrue;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we copy Services";
            Field_id.EnglishName		    =	"Duplicate Services";
			bSettings.AddSetting(Field_id);

            Field_id	                    =	new SettingItemSpecial(ST2C.ServiceDups,new BooleanDataType());
			Field_id.Order			        =	165;
            Field_id.Value			        =	StStr.strFalse;
			Field_id.Group                  =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			Field_id.ExtendedGroupName      =   extgrp1;
			Field_id.Description		    =	"Should we check duplicate Services";
            Field_id.EnglishName		    =	"Check for duplicates";
			bSettings.AddSetting(Field_id);

            if ( Crm2CrmTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Crm2CrmSI InitSettings END.",( Crm2CrmTrace.Sw.TraceVerbose ) ? Crm2CrmTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
    }

    /// <summary>
    /// There is a limitation in fetch xml, it return max 5000 records. And when we 
    /// execute mail merge the CRM fetch xml return max 5000 records for merge. 
    /// To overcome this problem we need to add a registry entry 
    /// “TurnOffFetchThrottling”, of type “DWORD” with value Non-zero. 
    /// (http://msdn.microsoft.com/en-us/library/aa682811.aspx - This is supported in CRM 4.0 also) 
    /// </summary>
    public partial class Crm2Crm : PortalCrmProgressModuleControl
    {
        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #region General implementation

        public override bool AdminModule
        {
            get
            {
                return false;
            }
        }

        public override Guid GuidID
        {
            get
            {
                return new Guid("{F42C8724-EE1C-4c47-B7CB-FA62421ECA2E}");
            }
        }
        #endregion General implementation

        #region local exception class
        class InnerException : Exception
        {
            public InnerException(string msg) : base(msg)
            {}
            public InnerException(string msg,Exception ex) : base(msg,ex)
            {}
        }

        class FatalException : Exception
        {
            public FatalException(string msg) : base(msg)
            {}
            public FatalException(string msg,Exception ex) : base(msg,ex)
            {}
        }
        #endregion local exception class

        #region properties

        const string strSourceUserId        =   "SourceUserId";
        const string strSourceDomainName    =   "SourceDomainName";
        const string strTargetDomainName    =   "TargetDomainName";
        const string strMappingData         =   "MappingData";

        int     errCount                    =   0;
        int     CreateCount                 =   0;
        int     DupCount                    =   0;
        int     UpdateCount                 =   0;
        int     TotErrorCount               =   0;
        int     TotCreateCount              =   0;
        int     TotDupCount                 =   0;
        int     TotUpdCount                 =   0;

        bool    NeedOpportunityClose        =  false;
        bool    NeedOrderClose              =  false;
        bool    NeedQuoteClose              =  false;

        
        string[] MustCheckDuplicates        =   new string[]
                                        {
                                        CrmStr.relationshiprole,CrmStr.relationshiprolemap,CrmStr.subject,CrmStr.template,CrmStr.productpricelevel,
                                        CrmStr.uom,CrmStr.uomschedule,CrmStr.discounttype,CrmStr.discount,CrmStr.pricelevel,
                                        CrmStr.contracttemplate,CrmStr.kbarticletemplate,CrmStr.resource,CrmStr.team,
                                        CrmStr.service,CrmStr.plugintype,CrmStr.workflow,CrmStr.pluginassembly,
                                        CrmStr.opportunityproduct,CrmStr.quotedetail,CrmStr.salesorderdetail,CrmStr.invoicedetail
                                        };

        string DocumentsFolder
        {
            get
            {
                bool UseDefault =   Settings[ST2C.UseSiteDefault].ToBool();
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DocumentsFolder UseSiteDefault: {0}.", UseDefault), Crm2CrmTrace.Sw.Info);
                if ( UseDefault )
                    return portalSettings.DefaultDocumentFolderPath; 
                string path =   Server.MapPath(Settings[ST2C.DocumentsFolder].FullPath);
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DocumentsFolder path: {0}.", path), Crm2CrmTrace.Sw.Info);
                return path;
            }
        }

        SortedList<string,int> _Records =   null;
        SortedList<string,int> Records
        {
            get
            {
                if ( _Records == null )
                {
                    if ( ViewState["Records"] != null )
                        _Records        =   (SortedList<string,int>)ViewState["Records"];
                    if ( _Records == null )
                        _Records        =   new SortedList<string,int>();
                }
                return _Records;
            }
            set
            {
                ViewState["Records"]    =   value;
                _Records                =   value;
                
            }
        }
        
        bool FindSystemUserByDomainName
        {
            get
            {
                return cbFindSystemUserByDomainName.Checked;
            }
        }
        
        bool TakeFirstDuplicateEvenIfMore
        {
            get
            {
                return CbFirstDuplicate.Checked;
            }
        }

        /// <summary>
        /// Should we check duplicates according input choices
        /// </summary>
        bool CheckDuplicates(string schemName)
        {
		    if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CheckDuplicates BEG SchemaName: {0}",schemName),Crm2CrmTrace.Sw.Info);
            switch(schemName)
            {
                case CrmStr.customeraddress:
                case CrmStr.competitor:
                case CrmStr.territory:
                case CrmStr.team:
                case CrmStr.lead:
                case CrmStr.contact:
                case CrmStr.account:
                    return CbCustomersDups.Checked;

                case CrmStr.relationshiprole:
                case CrmStr.subject:
                case CrmStr.salesliterature:
                case CrmStr.salesliteratureitem:
                case CrmStr.customerrelationship:
                    return CbCustomerRelationsDups.Checked;

                case CrmStr.uom:
                case CrmStr.uomschedule:
                case CrmStr.discounttype:
                case CrmStr.discount:
                case CrmStr.pricelevel:
                case CrmStr.productassociation:
                case CrmStr.productsalesliterature:
                case CrmStr.productsubstitute:
                case CrmStr.product:
                    return CbProducts.Checked;

                case CrmStr.customeropportunityrole:
                case CrmStr.opportunityproduct:
                case CrmStr.opportunityclose:
                case CrmStr.opportunity:
                    return CbOpportunitiesDups.Checked;

                case CrmStr.quoteclose:
                case CrmStr.quote:
                case CrmStr.quotedetail:
                    return CbQuotesDups.Checked;
                
                case CrmStr.orderclose:
                case CrmStr.salesorder:
                case CrmStr.salesorderdetail:
                    return CbOrdersDups.Checked;

                case CrmStr.invoice:
                case CrmStr.invoicedetail:
                    return CbInvoicesDups.Checked;

                case CrmStr.appointment:
                case CrmStr.template:
                case CrmStr.annotation:
                case CrmStr.phonecall:
                case CrmStr.letter:
                case CrmStr.email:
                case CrmStr.task:
                case CrmStr.fax:
                case CrmStr.activitypointer:
                    return CbActivitiesDups.Checked;
                case CrmStr.list:
                    return CbListsDups.Checked;

                case CrmStr.campaignactivity:
                case CrmStr.campaignresponse:
                case CrmStr.campaign:
                    return CbCampaignsDups.Checked;

                case CrmStr.contracttemplate:
                case CrmStr.contract:
                case CrmStr.contractdetail:
                    return CbContractsDups.Checked         =   Settings[ST2C.ContractsDups].ToBool();

                case CrmStr.calendar:
                case CrmStr.annualfiscalcalendar:
                case CrmStr.fixedmonthlyfiscalcalendar:
                case CrmStr.monthlyfiscalcalendar:
                case CrmStr.quarterlyfiscalcalendar:
                case CrmStr.semiannualfiscalcalendar:
                    return true;

                case CrmStr.site:
                case CrmStr.incident:
                case CrmStr.incidentresolution:
                case CrmStr.kbarticle:
                case CrmStr.kbarticlecomment:
                case CrmStr.kbarticletemplate:
                case CrmStr.equipment:
                case CrmStr.serviceappointment:
                case CrmStr.service:
                case CrmStr.resource:
                case CrmStr.resourcegroup:
                case CrmStr.constraintbasedgroup:
                case CrmStr.resourcespec:
                    return CbServiceDups.Checked;
                default:
                    bool ret    = cbDefaultCheckDup.Checked;  
		            if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CheckDuplicates no dedicated flag for SchemaName: {0}, ret: {1}.",schemName, ret),Crm2CrmTrace.Sw.Info);
                    return ret;
                }
        }

        bool ShoudCheckDuplicates(string schemName)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm ShoudCheckDuplicates BEG.",Crm2CrmTrace.Sw.Info );
            foreach(string str in MustCheckDuplicates)
                if ( str == schemName )
                    return true;
            if ( CheckDuplicates(schemName) )
                return true;
            if ( Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm ShoudCheckDuplicates END: false.",Crm2CrmTrace.Sw.Info );
            return false;
        }

        bool ShouldUpdate
        {
            get
            {
                return cbUpdateDuplicates.Checked;
            }
        }

        bool StopOnFirstError
        {
            get
            {
                return cbStopOnFirst.Checked;
            }
        }

        int MaxErrors
        {
            get
            {
                if (tbMaxErrors.Value.HasValue)
                    return (int)tbMaxErrors.Value.Value;
                return 100;
            }
        }

        bool CopyFromCrm3
        {
            get
            {
                return RdBtnCRMV3.Checked;
            }
        }

        // Copy All
        bool FullCopy
        {
            get
            {
                return CbCopyAll.Checked;
            }
        }

        // Copy all created after
        DateTime StartCreateDate
        {
            get
            {
                return CRMUtil.minDateTime; 
            }
        }

        #region Input parameters for crm4
        
        public string Organization
        {
            get
            {
                return RadTbOrganization.Text.Trim();
            }
        }

        public int Port
        {
            get
            {
                return (RadTbDiscoPort.Value.HasValue) ? (int)RadTbDiscoPort.Value.Value:80;
            }
        }

        string DiscoServerName
        {
            get
            {
                return RadTbDiscoServer.Text.Trim();
            }
        }

        ADNAuthenticationType AuthenticationType
        {
            get
            {
                ADNAuthenticationType tp =  (ADNAuthenticationType)Enum.Parse( typeof(ADNAuthenticationType), RadCbAuthentication.SelectedValue);
                return tp;
            }
        }

        #endregion CRM 4

        #region CRM 3 input params

        string _Url2            =   string.Empty;
        string Url2
        {
            get
            {
                if ( string.IsNullOrEmpty(_Url2 ) )
                {
                    _Url2       =   RadTbUrl.Text;
                }
                return _Url2;
            }
            set
            {
                _Url2               =   value;
                RadTbUrl.Text       =   value;
            }
        }

        #endregion CRM 3 input params

        #region Common input params

        string _CRMServiceAccount           =   string.Empty;
        string CRMServiceAccount
        {
            get
            {
                if ( string.IsNullOrEmpty(_CRMServiceAccount ) )
                {
                    _CRMServiceAccount      =   RadTbAccount.Text;
                }
                return _CRMServiceAccount;
            }
            set
            {
                _CRMServiceAccount          =   value;
                RadTbAccount.Text           =   value;
            }
        }
        string _CRMServicePassword          =   string.Empty;
        string CRMServicePassword
        {
            get
            {
                if ( string.IsNullOrEmpty(_CRMServicePassword ) )
                {
                    object ob               =   Session["Pwd"];
                    if ( ob != null )
                        _CRMServicePassword =   (string)ob;
                }
                return _CRMServicePassword;
            }
            set
            {
                _CRMServicePassword         =   value;
                Session["Pwd"]              =   value;
            }
        }

        string _CRMServiceDomain            =   string.Empty;
        string CRMServiceDomain
        {
            get
            {
                if ( string.IsNullOrEmpty(_CRMServiceDomain ) )
                {
                    _CRMServiceDomain       =   RadTbDomain.Text;
                }
                return _CRMServiceDomain;
            }
            set
            {
                _Url2                       =   value;
                RadTbDomain.Text            =   value;
            }
        }

        #endregion Common input params
        
        CRMWrapperBase _Wrapper2    =   null;
        public CRMWrapperBase Wrapper2
        {
            get
            {
                if (_Wrapper2 == null)
                {
				    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm StartWrapper BEG Url2: {0}, CRMServiceAccount: {1}, CRMServicePassword: {2}, CRMServiceDomain: {3}", 
                            new object[]{Url2, CRMServiceAccount, CRMServicePassword, CRMServiceDomain}),Crm2CrmTrace.Sw.Info);
                    bool UsePreAuthenticate =   Config.CRMUsePreAuthenticate;
                    // no need for anonymous here
                    if ( CopyFromCrm3 )
                    {
                        _Wrapper2           =   new CrmWrapper3(Url2,CRMServiceAccount,CRMServicePassword,CRMServiceDomain,
                                                        CRMServiceAccount,CRMServicePassword,CRMServiceDomain,CRMServiceAccount,CRMServicePassword,CRMServiceDomain);
                    }
                    else
                    {
                        _Wrapper2           =   new CrmWrapper4(Organization,DiscoServerName,Port,AuthenticationType,CRMServiceAccount, CRMServicePassword, CRMServiceDomain,
                                                        CRMServiceAccount, CRMServicePassword, CRMServiceDomain,CRMServiceAccount, CRMServicePassword, CRMServiceDomain,UsePreAuthenticate);
                    }
                    _Wrapper2.Initialize(UsePreAuthenticate);
				    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]Crm2Crm StartWrapper END Ok, initialized",Crm2CrmTrace.Sw.Info);
                }
                return _Wrapper2;
            }
        }

        string _entityName                                  = CrmStr.account;
        public string entityName
        {
            get { return _entityName; }
        }

        EntityConfig _TConfig2 = null;
        public EntityConfig TConfig2
        {
            get
            {
                if (_TConfig2 == null)
                {
                    _TConfig2       =   new EntityConfig(Wrapper2,entityName);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm TConfig2 Ctor entityName: {0}, vflag: [{1}], DisplayMask: [{2}].",
                            entityName,_TConfig2.entityFlags, _TConfig2.DisplayMask),Crm2CrmTrace.Sw.Info);
                }
                return _TConfig2;
            }
        }

        public EntityConfig NewTConfig2(string entName)
        {
            return new EntityConfig(Wrapper2,entName);
        }
        
        EntityConfig _TConfig = null;
        public EntityConfig TConfig
        {
            get
            {
                if (_TConfig == null)
                {
                    _TConfig = new EntityConfig(Wrapper,entityName);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm TConfig Ctor entityName: {0}, vflag: [{1}], DisplayMask: [{2}].",
                            entityName,_TConfig.entityFlags, _TConfig.DisplayMask),Crm2CrmTrace.Sw.Info);
                }
                return _TConfig;
            }
        }
        class State2Set
        {
            public DynEntity dynEn;
            public Guid PrimaryKeyValue;
            public int State;
            public int Status;

        }

        public class DicDynEnt : Dictionary<Guid, DynEntity>
        { }

        List<State2Set> Statu2SetList                   =   new List<State2Set>();
        List<DynEntity> dynEntList                      =   new List<DynEntity>();

        DicDynEnt RelationShipDic                       =   new DicDynEnt();
        Dictionary<string,DynEntity> Lookup2Set         =   new Dictionary<string,DynEntity>();
        Dictionary<string,DicDynEnt> DicDic             =   new Dictionary<string,DicDynEnt>();
        List<string> DicErrors                          =   new List<string>();
        internal class ResultCount
        {
            public int Copied       =   0;
            public int Created      =   0;
            public int Duplicates   =   0;
            public int Updated      =   0;
            public int Errors       =   0;
        }

        SortedList<string,ResultCount> DicOk            =   new SortedList<string,ResultCount>();

        #endregion properties

        /// <summary>
        /// Ctor we install parameters for duplication
        /// </summary>
        public Crm2Crm()
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose || Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Crm2CrmTrace Ctor BEG.",( Crm2CrmTrace.Sw.TraceVerbose ) ? Crm2CrmTrace.Sw.Info:Crm2CrmTrace.Sw.Info);
            ValidationGroup                 =   "Main";
            if ( Crm2CrmTrace.Sw.TraceVerbose || Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Crm2CrmTrace Ctor END.",( Crm2CrmTrace.Sw.TraceVerbose ) ? Crm2CrmTrace.Sw.Info:Crm2CrmTrace.Sw.Info);
        }
        
        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp             =   "CRM2CRM";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new Crm2CrmSI(bSettings,this);
        }

        string makeFullName(string orgFullName)
        {
            int fnv3             =   Wrapper2.FullNameFormat;
            int fnv4             =   Wrapper.FullNameFormat;
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm makeFullName  orgFullName: {0}, fnv4: {1}, fnv3: {2}.",orgFullName,fnv4,fnv3),Crm2CrmTrace.Sw.Info);
            if ( fnv4 == fnv3 )
                return orgFullName;
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm makeFullName  v4: {0}, v3: {1}.",Wrapper.FullNameFormatName,Wrapper2.FullNameFormatName),Crm2CrmTrace.Sw.Info);
            string firstName    =   string.Empty;
            string lastName     =   string.Empty;
            string midName      =   string.Empty;
            int idx             =   orgFullName.IndexOf(',');
            switch (fnv3)
            {
                case 0: //Last Name, First Name 
                    if (idx != -1)
                    {
                        lastName = orgFullName.Substring(0, idx).Trim();
                        firstName = orgFullName.Substring(idx + 1).Trim();
                    }
                    else
                    {
                        lastName    =   orgFullName;
                    }
                    break;
                case 1: //First Name
                    firstName       =   orgFullName;
                    break;

                case 2: //Last Name, First Name, Middle Initial
                    if (idx != -1)
                    {
                        lastName    =   orgFullName.Substring(0, idx).Trim();
                        midName     =   orgFullName.Substring(idx + 1).Trim();
                        idx         =   midName.IndexOf(',');
                        if (idx != -1)
                        {
                            firstName   =   midName.Substring(0, idx).Trim();
                            midName     =   midName.Substring(idx + 1).Trim();
                        }
                    }
                    else
                    {
                        lastName    =   orgFullName;
                    }
                    break;

                case 3: //First Name, Middle Initial, Last Name
                    if (idx != -1)
                    {
                        firstName   =   orgFullName.Substring(0, idx).Trim();
                        lastName    =   orgFullName.Substring(idx + 1).Trim();
                        idx         =   lastName.IndexOf(',');
                        if (idx != -1)
                        {
                            midName  =  lastName.Substring(0, idx).Trim();
                            lastName =  lastName.Substring(idx + 1).Trim();
                        }
                    }
                    else
                    {
                        lastName    =   orgFullName;
                    }
                    break;

                case 4: //Last Name, First Name, Middle Name
                    if (idx != -1)
                    {
                        lastName    =   orgFullName.Substring(0, idx).Trim();
                        firstName   =   orgFullName.Substring(idx + 1).Trim();
                        idx         =   firstName.IndexOf(',');
                        if (idx != -1)
                        {
                            firstName =  firstName.Substring(0, idx).Trim();
                            midName   =  firstName.Substring(idx + 1).Trim();
                        }
                    }
                    else
                    {
                        lastName    =   orgFullName;
                    }
                    break;

                case 5: //First Name, Middle Name, Last Name
                    if (idx != -1)
                    {
                        firstName   =   orgFullName.Substring(0, idx).Trim();
                        lastName    =   orgFullName.Substring(idx + 1).Trim();
                        idx         =   lastName.IndexOf(',');
                        if (idx != -1)
                        {
                            midName  =  lastName.Substring(0, idx).Trim();
                            lastName =  lastName.Substring(idx + 1).Trim();
                        }
                    }
                    else
                    {
                        lastName    =   orgFullName;
                    }
                    break;

                case 6: //Last Name, space, First Name
                    idx             =   orgFullName.IndexOf(' ');
                    if (idx != -1)
                    {
                        lastName    =   orgFullName.Substring(0, idx).Trim();
                        firstName   =   orgFullName.Substring(idx + 1).Trim();
                    }
                    else
                    {
                        lastName    =   orgFullName;
                    }
                    break;

                case 7: //Last Name, no space, First Name
                    lastName    =   orgFullName; // ??????
                    break;
            }
            string result   =   Wrapper.MakeFullName(firstName,lastName,midName);
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm makeFullName  orgFullName: {0}, result: {1}.",orgFullName,result),Crm2CrmTrace.Sw.Info);
            return result;
        }

        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose || Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm Page_Load BEG IsPostBack: {0}, IsInAsyncPostBack: {1}.", IsPostBack,IsInAsyncPostBack), (Crm2CrmTrace.Sw.TraceVerbose) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
            
            ModuleProgressArea              =   RadProgressArea1;
            // init localization string in progress manager/area
            InitProgress(); // Pb no persist between postback
            const string fmt                =   "realPostBack('{0}', ''); return false;";
            updateBtn.OnClientClick         =   string.Format(fmt, updateBtn.UniqueID);
            if (!IsPostBack)
            {
                InitData();
            }
            if (Crm2CrmTrace.Sw.TraceVerbose || Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm Page_Load END IsPostBack: {0}, IsInAsyncPostBack: {1}.", IsPostBack,IsInAsyncPostBack), (Crm2CrmTrace.Sw.TraceVerbose) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
        }

        void InitData()
        {
            // clean session from an eventual previous call
            Session.Remove("Pwd");
            Session.Remove(strMappingData);
            Session.Remove("DefaultTargetUser");
            Session.Remove("TargetUsers");
            Session.Remove("TargetUsers2");
            Session.Remove(strTargetDomainName);
            
            if ( Settings[ST2C.CRMVersion].ToString() == "4" )
                    RdBtnCRMV4.Checked      =   true;
            else    RdBtnCRMV3.Checked      =   true;
            
            RadLbCustomEnt.SelectedValue    =   string.Empty;

            RadTbOrganization.Text          =   Settings[ST2C.Organization].ToString();
            RadTbDiscoServer.Text           =   Settings[ST2C.DiscoServer].ToString();
            RadTbDiscoPort.Value            =   Settings[ST2C.DiscoPort].ToInt();
            RadTbUrl.Text                   =   Settings[ST2C.ServerUrl].ToString();
            RadTbAccount.Text               =   Settings[ST2C.Login].ToString();
            RadTbDomain.Text                =   Settings[ST2C.Domain].ToString();
            // Init copy parameters from settings
            CbCopyAll.Checked               =   Settings[ST2C.CopyAllDates].ToBool();
            if ( CbCopyAll.Checked )
                    RadStartDate.Enabled    =   false;
            else    RadStartDate.Enabled    =   true;
            CbFirstDuplicate.Checked        =   Settings[ST2C.FirstDuplicate].ToBool();
            cbDefaultCheckDup.Checked       =   Settings[ST2C.DefaultCheckDup].ToBool();
            cbUpdateDuplicates.Checked      =   Settings[ST2C.UpdateExisting].ToBool();
            CbCustomers.Checked             =   Settings[ST2C.Customers].ToBool();
            CbCustomersDups.Checked         =   Settings[ST2C.CustomersDups].ToBool();
            CbCustomerRelations.Checked     =   Settings[ST2C.CustomerRelations].ToBool();
            CbCustomerRelationsDups.Checked =   Settings[ST2C.CustomerRelationsDups].ToBool();
            CbProducts.Checked              =   Settings[ST2C.Products].ToBool();
            CbProductsDups.Checked          =   Settings[ST2C.ProductsDups].ToBool();
            CbOpportunities.Checked         =   Settings[ST2C.Opportunities].ToBool();
            CbOpportunitiesDups.Checked     =   Settings[ST2C.OpportunitiesDups].ToBool();
            CbQuotes.Checked                =   Settings[ST2C.Quotes].ToBool();
            CbQuotesDups.Checked            =   Settings[ST2C.QuotesDups].ToBool();
            CbOrders.Checked                =   Settings[ST2C.Orders].ToBool();
            CbOrdersDups.Checked            =   Settings[ST2C.OrdersDups].ToBool();
            CbInvoices.Checked              =   Settings[ST2C.Invoices].ToBool();
            CbInvoicesDups.Checked          =   Settings[ST2C.InvoicesDups].ToBool();
            CbActivities.Checked            =   Settings[ST2C.Activities].ToBool();
            CbActivitiesDups.Checked        =   Settings[ST2C.ActivitiesDups].ToBool();
            CbLists.Checked                 =   Settings[ST2C.Lists].ToBool();
            CbListsDups.Checked             =   Settings[ST2C.ListsDups].ToBool();
            CbCampaigns.Checked             =   Settings[ST2C.Campaigns].ToBool();
            CbCampaignsDups.Checked         =   Settings[ST2C.CampaignsDups].ToBool();
            CbContracts.Checked             =   Settings[ST2C.Contracts].ToBool();
            CbContractsDups.Checked         =   Settings[ST2C.ContractsDups].ToBool();
            CbService.Checked               =   Settings[ST2C.Service].ToBool();
            CbServiceDups.Checked           =   Settings[ST2C.ServiceDups].ToBool();
            CbCalendar.Checked              =   Settings[ST2C.Calendars].ToBool();
            
            // this is simply a gui button to enable or disable all checking
            cbCheckDuplicates.Checked       =   (cbUpdateDuplicates.Checked && CbCustomersDups.Checked && CbCustomerRelationsDups.Checked &&
            CbProductsDups.Checked && CbOpportunitiesDups.Checked && CbQuotesDups.Checked && CbOrdersDups.Checked  && CbInvoicesDups.Checked &&
            CbActivitiesDups.Checked && CbListsDups.Checked && CbCampaignsDups.Checked  && CbContractsDups.Checked  &&  CbServiceDups.Checked );
            
            RadGrid1.DataSource             =   null;
            if ( IsPostBack ) // will be done automatically and in time when !IsPostBack
                RadGrid1.Rebind();
        }

        /// <summary>
        /// We try to find entity in v3 then in v4, if not found we create it and add to List
        /// </summary>
        public List<DynEntity> DuplicateCalendarRules(DynEntity orgCdr, DynEntity newAcc, string Name, InternalDynamicEntityArray Val)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicateCalendarRules BEG Name: [{0}].", Name),Crm2CrmTrace.Sw.Info);
            List<DynEntity> Lst             =   new List<DynEntity>();
            List<DynEntity> destLst         =   new List<DynEntity>();
            PropertyDescriptorCollection _columnDescriptors     =   null;
            EntityConfig TConf2             =   new EntityConfig(Wrapper2,CrmStr.calendarrule);
            Wrapper2.Util.ExecForEachDynamicEntity(Val,delegate(InternalDynamicEntity de)
                {
                    DynEntity ob            =   new DynEntity(Wrapper2, de, _columnDescriptors,null);
                    string Schem            =   ob.SchemaName;
                    ob.EntityMData          =   TConf2.entityMetaData;
                    // force generation but do not use for next value because could be from a different entity
                    _columnDescriptors      =   ob.PropertyDescriptorCollection;
                    Lst.Add(ob);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicateCalendarRules added objectname: [{0}].", ob.SchemaName),Crm2CrmTrace.Sw.Info);
                    return true;
                });
            int count                       =   Lst.Count;
            EntityConfig TConf              =   new EntityConfig(Wrapper,CrmStr.calendarrule);
            if ( Crm2CrmTrace.Sw.TraceVerbose || Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicateCalendarRules Name: [{0}], Count: {1}.", Name,count),(Crm2CrmTrace.Sw.TraceVerbose) ? Crm2CrmTrace.Sw.Info:Crm2CrmTrace.Sw.Info);
            for (int i = 0; i < count; i++)
            {
                DynEntity s                 =   Lst[i];
                DynEntity newAp             =   null;
                if (DicDic.ContainsKey(CrmStr.calendarrule) && DicDic[CrmStr.calendarrule].ContainsKey(s.PrimaryKeyGuidValue))
                {
                    newAp                   =   DicDic[CrmStr.calendarrule][s.PrimaryKeyGuidValue];
                }
                else
                {
                    newAp                   =   CopyDynEntity(s, TConf, orgCdr.PrimaryKeyGuidValue);// we snd the calendarid as specific calendarrule copy parameter to avoid reentrencies
                    
                    DicDynEnt dic           =   null;
                    if ( !DicDic.ContainsKey(CrmStr.calendarrule) )
                    {
                        dic                 =   new DicDynEnt();
                        DicDic.Add(CrmStr.calendarrule, dic);
                    }
                    else dic                =   DicDic[CrmStr.calendarrule];
                    if ( !dic.ContainsKey(s.PrimaryKeyGuidValue) )
                        dic.Add(s.PrimaryKeyGuidValue,newAcc);
                }
                destLst.Add(newAp);
            }
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicateCalendarRules END found count: [{0}].",destLst.Count),Crm2CrmTrace.Sw.Info);
            if (destLst.Count > 0)
            {
                InternalDynamicEntityArray newArray = Wrapper.Util.MakeDynamicArray(destLst);
                newAcc.AddDynamicEntityArrayProperty(Name, newArray);
            }
            return destLst;
        }

        /// <summary>
        /// We try to find entity in v3 then in v4, if not found we create it and add to List
        /// </summary>
        public void DuplicatePartyList(DynEntity newAcc, string Name, InternalDynamicEntityArray Val)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicatePartyList BEG Name: [{0}].", Name),Crm2CrmTrace.Sw.Info);
            List<DynEntity> Lst                 =   new List<DynEntity>();
            List<DynEntity> destLst             =   new List<DynEntity>();
            PropertyDescriptorCollection _columnDescriptors     =   null;
            Wrapper2.Util.ExecForEachDynamicEntity
                (Val,
                 delegate(InternalDynamicEntity de)
                {
                    DynEntity ob                =   new DynEntity(Wrapper2, de, null,null);
                    string Schem                =   ob.SchemaName;
                    ob.EntityMData              =   new EntityConfig(Wrapper2,Schem).entityMetaData;
                    // force generation but do not use for next value because could be from a different entity
                    _columnDescriptors          =   ob.PropertyDescriptorCollection;
                    Lst.Add(ob);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicatePartyList added objectname: [{0}].", ob.SchemaName),Crm2CrmTrace.Sw.Info);
                    return true;
                }
                );
                int count                       =   Lst.Count;
                if ( Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicatePartyList Name: [{0}], Count: {1}.", Name,count),Crm2CrmTrace.Sw.Info);
                for (int i = 0; i < count; i++)
                {
                    DynEntity s                 =   Lst[i];
                    Guid EntityID               = s.PrimaryKeyGuidValue;
                    if (EntityID != Guid.Empty)
                    {
                        switch (s.SchemaName)
                        {
                            case CrmStr.systemuser:
                            case CrmStr.contact:
                            case CrmStr.account:
                            case CrmStr.lead:
                                if (DicDic[s.SchemaName].ContainsKey(EntityID))
                                    destLst.Add(DicDic[s.SchemaName][EntityID]);
                                break;
                            case CrmStr.activityparty:
                                DynEntity newAp     =   new DynEntity(Wrapper, CrmStr.activityparty);
                                bool foundLookup    =   false;
                                Wrapper2.Util.ExecForEachDynamicEntityProperty(s,
                                        delegate(string Nm, object Vl, object val2, object val3, AttributeInternalType tp)
                                        {
                                            switch (tp)
                                            {
                                                case AttributeInternalType.Float:
                                                    if ( Vl is double )
                                                          newAp.AddFloatProperty(Name,(double)Vl);
                                                    else  newAp.AddFloatProperty(Nm, (float)Vl);
                                                    break;
                                                case AttributeInternalType.Picklist:
                                                    newAp.AddPicklistProperty(Nm, (int)Vl);
                                                    break;
                                                case AttributeInternalType.String:
                                                    newAp.AddStringProperty(Nm, (string)Vl);
                                                    break;
                                                case AttributeInternalType.DateTime:
                                                    newAp.AddDateTimeProperty(Nm, (string)Vl);
                                                    break;
                                                case AttributeInternalType.Boolean:
                                                    newAp.AddBooleanProperty(Nm, (bool)Vl);
                                                    break;
                                                case AttributeInternalType.PrimaryKey:
                                                    break;
                                                case AttributeInternalType.Lookup:
                                                    if (Nm == CrmStr.activityid) // not needed on create
                                                        break;
                                                    RetrieveLookup(newAp, Nm, (Guid)Vl, val3, null,val2);
                                                    foundLookup = true;
                                                    break;
                                                default:
                                                    if (Crm2CrmTrace.Sw.TraceError)
                                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm DuplicatePartyList missing column: [{0}], type: {1}.", Nm, tp), Crm2CrmTrace.Sw.Info);
                                                    break;
                                            }
                                            return true;
                                        });
                                if (foundLookup)
                                {
                                    destLst.Add(newAp);
                                    if (Crm2CrmTrace.Sw.TraceVerbose)
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicatePartyList added : [{0}]", newAp.PrimaryFieldStringValue), Crm2CrmTrace.Sw.Info);
                                }
                                break;
                        }
                    }
                }
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm DuplicatePartyList END found count: [{0}].",destLst.Count),Crm2CrmTrace.Sw.Info);
            if (destLst.Count > 0)
            {
                InternalDynamicEntityArray newArray =   Wrapper.Util.MakeDynamicArray(destLst);
                newAcc.AddDynamicEntityArrayProperty(Name, newArray);
            }
        }

        bool FindUniqueIdentifier(DynEntity s,string propertyname,string SchemaName,Guid Val)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FindUniqueIdentifier BEG propertyname: {0}, SchemaName: {1}, Val: {2}",
                    propertyname,SchemaName,Val), Crm2CrmTrace.Sw.Info);
            if ( DicDic.ContainsKey(SchemaName) && DicDic[SchemaName].ContainsKey(Val) )
            {
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FindUniqueIdentifier found: {0}, ID: {1}.",SchemaName,Val), Crm2CrmTrace.Sw.Info);
                s.AddUniqueIdentifierProperty(propertyname,DicDic[SchemaName][Val].PrimaryKeyGuidValue);
                return true;
            }
            DynEntity orgEnt    =   new DynEntity(Wrapper2,SchemaName,Val);
            if ( !orgEnt.adminRetrieve() )
                return false;
            bool created        =   false;
            DynEntity newDyn    =   Wrapper.Util.FindEntityByStringField(SchemaName,orgEnt.PrimaryFieldName,orgEnt.PrimaryFieldStringValue, false, ref created);
            if ( newDyn != null )
            {
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FindUniqueIdentifier END found SchemaName: {0}, Val: {1}",
                        SchemaName,Val), Crm2CrmTrace.Sw.Info);
                s.AddUniqueIdentifierProperty(propertyname,newDyn.PrimaryKeyGuidValue);
                return true;
            }
            return false;
        }

        /// <summary>
        /// Use a Webclient to get a file from CRM, return the byte array
        /// </summary>
        byte[] DownLoadFile(string url,ref bool OkDownload)
        {
            byte[] data                             =   null;
            bool Ok                                 =   false;
            try
            {
                data                                =   Wrapper2.DownLoadFile(url,ref Ok);
                OkDownload                          =   true;
            }
            catch (Exception ex)
            {
                string msg                          =   string.Format("[E]Crm2Crm DownLoadFile url '{0}', ex: {1}.", url, ex);
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine(msg,  (Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                DicErrors.Add(string.Format("Download for {0} failed.",url));
            }
            return data;
        }

        /*
            customerid Gets or sets the ID of the primary customer in the relationship. 
            customerroleid Gets or sets the ID of the customer role. 
            partnerid Gets or sets the ID of the secondary customer in the relationship. 
            partnerroleid Gets or sets the ID of the relationship role of the secondary customer. 
         */
        bool ExistCustomerRelationshipDuplicates(Guid customerid,Guid customerroleid,Guid partnerid,Guid partnerroleid,ref DynEntity newDyn)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistCustomerRelationshipDuplicates BEG customerid: {0}, customerroleid: {1}, partnerid: {2}, partnerroleid: {3}", 
                                new object[] {customerid,customerroleid,partnerid,partnerroleid}),Crm2CrmTrace.Sw.Info);
            GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.customerrelationship);
            InternalQueryExpression qe                          =   new InternalQueryExpression();
            qe.EntityName                                       =   CrmStr.customerrelationship;
            InternalAllColumns RequestCols                      =   new InternalAllColumns();
            InternalFilterExpression fi                         =   new InternalFilterExpression();
            InternalConditionExpression ex                      =   new InternalConditionExpression();
            ex.AttributeName                                    =   CrmStr.customerid;
            ex.Operator                                         =   InternalConditionOperator.Equal;
            ex.Values                                           =   new string[]{customerid.ToString()};
            InternalConditionExpression ex1                     =   new InternalConditionExpression();
            ex1.AttributeName                                   =   CrmStr.customerroleid;
            ex1.Operator                                        =   InternalConditionOperator.Equal;
            ex1.Values                                          =   new string[]{customerroleid.ToString()};
            InternalConditionExpression ex2                     =   new InternalConditionExpression();
            ex2.AttributeName                                   =   CrmStr.partnerid;
            ex2.Operator                                        =   InternalConditionOperator.Equal;
            ex2.Values                                          =   new string[]{partnerid.ToString()};
            InternalConditionExpression ex3                     =   new InternalConditionExpression();
            ex3.AttributeName                                   =   CrmStr.partnerroleid;
            ex3.Operator                                        =   InternalConditionOperator.Equal;
            ex2.Values                                          =   new string[]{partnerroleid.ToString()};
            fi.Conditions                                       =   new InternalConditionExpression[]{ex,ex1,ex2,ex3};
            qe.ColumnSet                                        =   RequestCols;
            qe.Criteria                                         =   fi;
            InternalBusinessEntityCollection allEnt             =   allEntQuery.adminRetrieve(qe);
            DynEntity ob                                        =   null;
            if ( allEntQuery.RetrievedCount > 0 )
            {
                // Transform them in DynEntities and insert them in dynEntList
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                        ob                                      =   DynEntity.CreateFromDynamicEntity(Wrapper,de,null);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistCustomerRelationshipDuplicates found PrimaryKeyGuidValue: {0}", ob.PrimaryKeyGuidValue),Crm2CrmTrace.Sw.Info);
                        return false; // stop, found
                    });
                newDyn                                          =   ob;
            }
            bool found                                          =   (ob != null );
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistCustomerRelationshipDuplicates END found: {0}", found),Crm2CrmTrace.Sw.Info);
            return found;
        }

        /// <summary>
        ///  Used to check for duplicae just before creating the copy, because we need all the attributes
        /// </summary>
        bool ExistRelationshipRoleMapDuplicates(string associateobjecttypecode,string primaryobjecttypecode,Guid relationshiproleid,ref DynEntity newDyn)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistRelationshipRoleMapDuplicates BEG associateobjecttypecode: {0}, primaryobjecttypecode: {1}, relationshiproleid: {2}", 
                    associateobjecttypecode,primaryobjecttypecode,relationshiproleid),Crm2CrmTrace.Sw.Info);
            GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.relationshiprolemap);
            InternalQueryExpression qe                          =   new InternalQueryExpression();
            qe.EntityName                                       =   CrmStr.relationshiprolemap;
            InternalAllColumns RequestCols                      =   new InternalAllColumns();
            InternalFilterExpression fi                         =   new InternalFilterExpression();
            InternalConditionExpression ex                      =   new InternalConditionExpression();
            ex.AttributeName                                    =   CrmStr.associateobjecttypecode;
            ex.Operator                                         =   InternalConditionOperator.Equal;
            ex.Values                                           =   new string[]{associateobjecttypecode};
            InternalConditionExpression ex1                     =   new InternalConditionExpression();
            ex1.AttributeName                                   =   CrmStr.primaryobjecttypecode;
            ex1.Operator                                        =   InternalConditionOperator.Equal;
            ex1.Values                                          =   new string[]{primaryobjecttypecode};
            InternalConditionExpression ex2                     =   new InternalConditionExpression();
            ex2.AttributeName                                   =   CrmStr.relationshiproleid;
            ex2.Operator                                        =   InternalConditionOperator.Equal;
            ex2.Values                                          =   new string[]{relationshiproleid.ToString()};
            fi.Conditions                                       =   new InternalConditionExpression[]{ex,ex1,ex2};
            qe.ColumnSet                                        =   RequestCols;
            qe.Criteria                                         =   fi;
            InternalBusinessEntityCollection allEnt             =   allEntQuery.adminRetrieve(qe);
            DynEntity ob                                        =   null;
            if ( allEntQuery.RetrievedCount > 0 )
            {
                // Transform them in DynEntities and insert them in dynEntList
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                        ob                                      =   DynEntity.CreateFromDynamicEntity(Wrapper,de,null);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistRelationshipRoleMapDuplicates found PrimaryKeyGuidValue: {0}", ob.PrimaryKeyGuidValue),Crm2CrmTrace.Sw.Info);
                        return false; // stop, found!
                    }
                    );
                newDyn                                          =   ob;
            }
            bool found                                          =   (ob != null );
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistRelationshipRoleMapDuplicates END found: {0}", found),Crm2CrmTrace.Sw.Info);
            return found;
        }
        
        /// <summary>
        /// Test duplicates for entities without a PrimaryField
        /// </summary>
        bool ExistNPRimaryFieldDuplicates(string SchemaName,DynEntity s,ref DynEntity newDyn)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistNPRimaryFieldDuplicates BEG duplicate SchemaName: {0}, PrimaryKeyGuidValue: {1}",
                    SchemaName,s.PrimaryKeyGuidValue), Crm2CrmTrace.Sw.Info);
            bool found                          =   false;
            Guid prodID                         =   Guid.Empty;
            switch(SchemaName)
            {
                case CrmStr.orderdetail: // find it by selecting same order same product same quantity and same amount
                    ADNDynSalesOrderDetail d    =   (ADNDynSalesOrderDetail)s;
                    Guid orderID                =   d.salesorderid;
                    if ( !DicDic.ContainsKey(CrmStr.salesorder) || !DicDic[CrmStr.salesorder].ContainsKey(orderID) ) // order not found so no way o check dup
                        break;
                    orderID                     =   ((ADNDynSalesOrder)DicDic[CrmStr.salesorder][orderID]).salesorderid;
                    prodID                      =   d.productid;
                    if ( !DicDic.ContainsKey(CrmStr.product) || !DicDic[CrmStr.product].ContainsKey(prodID) ) // product not found so no way o check dup
                        break;
                    prodID                      =   ((ADNDynProduct)DicDic[CrmStr.product][prodID]).productid;
                    ADNDynSalesOrderDetail newSD=   new ADNDynSalesOrderDetail(Wrapper);
                    found                       =   newSD.FindByOrderProduct(ResetWrapper,orderID,prodID,d.quantity,d.priceperunit);
                    if ( found )
                        newDyn                  =   newSD;
                    break;
                case CrmStr.quotedetail: // find it by selecting same order same product same quantity and same amount
                    ADNDynQuoteDetail q         =   (ADNDynQuoteDetail)s;
                    Guid quoteID                =   q.quoteid;
                    if ( !DicDic.ContainsKey(CrmStr.quote) || !DicDic[CrmStr.quote].ContainsKey(quoteID) ) // order not found so no way o check dup
                        break;
                    quoteID                     =   ((ADNDynQuote)DicDic[CrmStr.quote][quoteID]).quoteid;
                    prodID                      =   q.productid;
                    if ( !DicDic.ContainsKey(CrmStr.product) || !DicDic[CrmStr.product].ContainsKey(prodID) ) // product not found so no way o check dup
                        break;
                    prodID                      =   ((ADNDynProduct)DicDic[CrmStr.product][prodID]).productid;
                    ADNDynQuoteDetail newQD     =   new ADNDynQuoteDetail(Wrapper);
                    found                       =   newQD.FindByQuoteProduct(ResetWrapper,quoteID,prodID,q.quantity,q.priceperunit);
                    if ( found )
                        newDyn                  =   newQD;
                    break;
                case CrmStr.invoicedetail: // find it by selecting same order same product same quantity and same amount
                    ADNDynInvoiceDetail iv      =   (ADNDynInvoiceDetail)s;
                    Guid ivID                   =   iv.invoiceid;
                    if ( !DicDic.ContainsKey(CrmStr.invoice) || !DicDic[CrmStr.invoice].ContainsKey(ivID) ) // order not found so no way o check dup
                        break;
                    ivID                        =   ((ADNDynInvoice)DicDic[CrmStr.invoice][ivID]).invoiceid;
                    prodID                      =   iv.productid;
                    if ( !DicDic.ContainsKey(CrmStr.product) || !DicDic[CrmStr.product].ContainsKey(prodID) ) // product not found so no way o check dup
                        break;
                    prodID                      =   ((ADNDynProduct)DicDic[CrmStr.product][prodID]).productid;
                    ADNDynInvoiceDetail newID   =   new ADNDynInvoiceDetail(Wrapper);
                    found                       =   newID.FindByInvoiceProduct(ResetWrapper,ivID,prodID,iv.quantity,iv.priceperunit);
                    if ( found )
                        newDyn                  =   newID;
                    break;
                case CrmStr.productpricelevel: // find it by selecting same product and same pricelevel
                    ADNDynProductPricelevel pl  =   (ADNDynProductPricelevel)s;
                    Guid plID                   =   pl.pricelevelid;
                    if ( !DicDic.ContainsKey(CrmStr.pricelevel) || !DicDic[CrmStr.pricelevel].ContainsKey(plID) ) // pricelevel not found so no way o check dup
                        break;
                    plID                        =   ((ADNDynPricelevel)DicDic[CrmStr.pricelevel][plID]).pricelevelid;
                    prodID                      =   pl.productid;
                    if ( !DicDic.ContainsKey(CrmStr.product) || !DicDic[CrmStr.product].ContainsKey(prodID) ) // product not found so no way o check dup
                        break;
                    prodID                      =   ((ADNDynProduct)DicDic[CrmStr.product][prodID]).productid;

                    Guid UnitID                 =   pl.uomid;
                    if ( !DicDic.ContainsKey(CrmStr.uom) || !DicDic[CrmStr.uom].ContainsKey(UnitID) ) // unit not found so no way o check dup
                        break;
                    UnitID                      =   ((ADNDynUom)DicDic[CrmStr.uom][UnitID]).uomid;
                    
                    ADNDynProductPricelevel nPl =   new ADNDynProductPricelevel(Wrapper);
                    found                       =   nPl.FindByPricelevelProduct(ResetWrapper,plID,prodID,UnitID,true);
                    if ( found )
                        newDyn                  =   nPl;
                    break;
            }
            if ( found )
            {
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistNPRimaryFieldDuplicates found SchemaName: {0}, PrimaryKeyGuidValue: {1}",
                    SchemaName,s.PrimaryKeyGuidValue), Crm2CrmTrace.Sw.Info);
                return true;
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistNPRimaryFieldDuplicates END NOT FOUND SchemaName: {0}, PrimaryKeyGuidValue: {1}",
                    SchemaName,s.PrimaryKeyGuidValue), Crm2CrmTrace.Sw.Info);
            return false;
        }

        /// <summary>
        /// Test duplicates for entities with a PrimaryField
        /// </summary>
        bool ExistDuplicates(DynEntity orgDyn,string searchVal,ref DynEntity newDyn)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicates BEG duplicate searchFieldName: {0}, SchemaName: {1}, searchVal: {2}",
                    orgDyn.PrimaryFieldName,orgDyn.SchemaName,searchVal), Crm2CrmTrace.Sw.Info);
            string SchemaName                                   =   orgDyn.SchemaName;
            string searchFieldName                              =   orgDyn.PrimaryFieldName;
            bool created                                        =   false;
            newDyn                                              =   Wrapper.Util.FindEntityByStringField(SchemaName,searchFieldName,searchVal, false, ref created);
            if ( newDyn != null )
            {
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicates found searchFieldName: {0}, searchVal: {1}",
                        searchFieldName,searchVal), Crm2CrmTrace.Sw.Info);
                return true;
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicates END NOT FOUND searchFieldName: {0}, SchemaName: {1}",
                    searchFieldName,SchemaName), Crm2CrmTrace.Sw.Info);
            return false;
        }

        /// <summary>
        /// Test duplicates for entities with a PrimaryField
        /// Take first duplicate if several exist
        /// </summary>
        bool ExistDuplicatesExt(DynEntity orgDyn,string searchAtt1,string searchAtt2,string searchVal2,ref DynEntity newDyn)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicatesExt BEG duplicate SchemaName: {0}, searchAtt1: {1}, searchAtt2: {2}",
                    orgDyn.SchemaName,searchAtt1,searchAtt2), Crm2CrmTrace.Sw.Info);
            string SchemaName                                   =   orgDyn.SchemaName;
            string searchField1Name                             =   searchAtt1;
            string searchField2Name                             =   searchAtt2;

            InternalQueryExpression qe                          =   new InternalQueryExpression();
            qe.EntityName                                       =   SchemaName;
            InternalAllColumns RequestCols                      =   new InternalAllColumns();
            InternalFilterExpression fi                         =   new InternalFilterExpression();
            InternalConditionExpression ex                      =   new InternalConditionExpression();
            ex.AttributeName                                    =   searchAtt1;
            ex.Operator                                         =   InternalConditionOperator.Equal;
            string val1                                         =   Wrapper2.GetPropertyValue(orgDyn[searchAtt1]).ToString();
            ex.Values                                           =   new string[] { val1 };
            InternalConditionExpression ex1                     =   new InternalConditionExpression();
            ex1.AttributeName                                   =   searchAtt2;
            ex1.Operator                                        =   InternalConditionOperator.Equal;
            ex1.Values                                          =   new string[] { searchVal2 };
            fi.Conditions                                       =   new InternalConditionExpression[] { ex,ex1 };
            qe.ColumnSet                                        =   RequestCols;
            qe.Criteria                                         =   fi;
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicatesExt search request searchField1: {0} ='{1}', searchField2: {2}='{3}'",
                    new object[]{searchField1Name,val1,searchField2Name,searchVal2}), Crm2CrmTrace.Sw.Info);
            int cntf                                            =   0;
            newDyn                                              =   DynEntity.FindEntityByQuery(Wrapper,SchemaName,qe,ResetWrapper,ref cntf,!TakeFirstDuplicateEvenIfMore,null);// we take first one if several
            if ( newDyn != null )
            {
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicatesExt found searchField1: {0}, val1: '{1}', searchField2: {2}, val2: '{3}', found: {4}",
                        new object[]{searchField1Name,val1,searchField2Name,searchVal2,cntf}), Crm2CrmTrace.Sw.Info);
                return true;
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicatesExt NOT found searchField1: {0}, searchField2: {1}",
                        searchField1Name,searchField2Name), Crm2CrmTrace.Sw.Info);
            return false;
        }

        /// <summary>
        /// Test duplicates for entities based on 1 corresponding field (orginally done for calendar)
        /// Dupliacte is selected if only one replicate exists
        /// </summary>
        bool ExistDuplicates1Factor(DynEntity orgDyn,string searchAtt1,string searchVal1,ref DynEntity newDyn)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicates1Factor BEG duplicate SchemaName: {0}, searchAtt1: {1}, searchVal1: {2}",
                    orgDyn.SchemaName,searchAtt1,searchVal1), Crm2CrmTrace.Sw.Info);
            string SchemaName                                   =   orgDyn.SchemaName;
            string searchField1Name                             =   searchAtt1;

            InternalQueryExpression qe                          =   new InternalQueryExpression();
            qe.EntityName                                       =   SchemaName;
            InternalAllColumns RequestCols                      =   new InternalAllColumns();
            InternalFilterExpression fi                         =   new InternalFilterExpression();
            InternalConditionExpression ex                      =   new InternalConditionExpression();
            ex.AttributeName                                    =   searchAtt1;
            ex.Operator                                         =   InternalConditionOperator.Equal;
            ex.Values                                           =   new string[] { searchVal1 };
            fi.Conditions                                       =   new InternalConditionExpression[] { ex};
            qe.ColumnSet                                        =   RequestCols;
            qe.Criteria                                         =   fi;
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicates1Factor search request searchField1: {0} ='{1}'",
                    new object[]{searchField1Name,searchVal1}), Crm2CrmTrace.Sw.Info);
            
            int cntf                                            =   0;
            newDyn                                              =   DynEntity.FindEntityByQuery(Wrapper,SchemaName,qe,ResetWrapper,ref cntf,!TakeFirstDuplicateEvenIfMore,null);// we take if only one exists
            if ( newDyn != null )
            {
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicates1Factor found searchField1: {0}, val1: '{1}', cnt: {2}",
                        new object[]{searchField1Name,searchVal1,cntf}), Crm2CrmTrace.Sw.Info);
                return true;
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ExistDuplicates1Factor NOT found searchField1: {0}, searchVal1: {1}, cnt: {2}",
                        searchField1Name,searchVal1,cntf), Crm2CrmTrace.Sw.Info);
            return false;
        }

        int CopyKitMembers(ADNDynProduct s,ADNDynProduct newAcc,EntityConfig TConfDest)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyKitMembers BEG source: {0}",s.name),Crm2CrmTrace.Sw.Info);
            int count                                               =   0;
            try
            {
                List<ADNDynProduct> List                            =   s.GetKitMembers(ResetWrapper,true);
                // Duplicate the members
                count                                               =   List.Count;
                ResetProgressSecTotal(count);
                SetUpdateProgress(string.Format("Copy {0} Kit members",s.name),ProgressPrimCount,ProgressSecCount);
                if (Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyKitMembers before copying Product Kit: {0}, members Count: {1}.",s.name,count),Crm2CrmTrace.Sw.Info);
                for (int i = 0; i < count; i++)
                {
                    ADNDynProduct m                                 =   List[i];
                    string PrimaryFieldStringValue                  =   m.name;
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyKitMembers Copy process product: {0}, i: {1}/{2}",PrimaryFieldStringValue, i+1,count), Crm2CrmTrace.Sw.Info);
                    SetUpdateProgress(string.Format("{0} '{1}'",s.name,PrimaryFieldStringValue),ProgressPrimCount,ProgressSecCount++);
                    // filter for already created records
                    ADNDynProduct dynTarget                         =   null;
                    if ( DicDic.ContainsKey(CrmStr.product) && DicDic[CrmStr.product].ContainsKey(m.productid) )
                    {
                        dynTarget                                   =   (ADNDynProduct)DicDic[CrmStr.product][m.productid];
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyKitMembers product already retrieved: {0}.",PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                    }
                    else
                    {
                        dynTarget                                   =   (ADNDynProduct)CopyDynEntity(m,TConfDest,null);
                    }
                    // Add target to Kit
                    newAcc.AddProductToKit(dynTarget,true);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyKitMembers added {0}.",PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                }
            }
            catch (InnerException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string msg          =   string.Format("[E]Crm2Crm CopyKitMembers ex : {0}", ex);
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                DicErrors.Add(string.Format("Copy Kit Members failed for {0}.",s.name));
                throw new InnerException(msg,ex);
            }

            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyKitMembers END found: {0}", count),Crm2CrmTrace.Sw.Info);
            return count;
        }
        
        int CopySubstitutes(ADNDynProduct s,ADNDynProduct newAcc,EntityConfig TConfDest)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopySubstitutes BEG source: {0}.",s.name),Crm2CrmTrace.Sw.Info);
            int count                                               =   0;
            try
            {
                List<ADNDynProduct> List                            =   s.GetSubstitutes(ResetWrapper,true);
                // Duplicate the members
                count                                               =   List.Count;
                ResetProgressSecTotal(count);
                SetUpdateProgress(string.Format("Copy {0} Substitues",s.name),ProgressPrimCount,ProgressSecCount);
                if (Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopySubstitutes before copying Product Kit: {0}, members Count: {1}.",s.name,count),Crm2CrmTrace.Sw.Info);
                for (int i = 0; i < count; i++)
                {
                    ADNDynProduct m                                 =   List[i];
                    string PrimaryFieldStringValue                  =   m.name;
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopySubstitutes Copy process product: {0}, i: {1}/{2}",PrimaryFieldStringValue, i+1,count), Crm2CrmTrace.Sw.Info);
                    SetUpdateProgress(string.Format("{0} '{1}'",s.name,PrimaryFieldStringValue),ProgressPrimCount,ProgressSecCount++);
                    // filter for already created records
                    ADNDynProduct dynTarget                         =   null;
                    if ( DicDic.ContainsKey(CrmStr.product) && DicDic[CrmStr.product].ContainsKey(m.productid) )
                    {
                        dynTarget                                   =   (ADNDynProduct)DicDic[CrmStr.product][m.productid];
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopySubstitutes product already retrieved: {0}.",PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                    }
                    else
                    {
                        dynTarget                                   =   (ADNDynProduct)CopyDynEntity(m,TConfDest,null);
                    }
                    // Add target to Kit
                    newAcc.AddSubstituteProduct(dynTarget,true);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopySubstitutes added {0}.",PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                }
            }
            catch (InnerException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string msg          =   string.Format("[E]Crm2Crm CopySubstitutes ex : {0}", ex);
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                DicErrors.Add(string.Format("Copy Subsititutes failed for {0}.",s.name));
                throw new InnerException(msg,ex);
            }

            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopySubstitutes END found: {0}", count),Crm2CrmTrace.Sw.Info);
            return count;
        }

        int CopyRelatedProducts(ADNDynSalesLiterature s,ADNDynSalesLiterature newAcc,EntityConfig TConfDest)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyRelatedProducts BEG source: {0}.",s.name),Crm2CrmTrace.Sw.Info);
            int count                                               =   0;
            try
            {
                List<ADNDynProduct> List                            =   s.GetRelatedProducts(ResetWrapper,true);
                // Duplicate the members
                count                                               =   List.Count;
                ResetProgressSecTotal(count);
                SetUpdateProgress(string.Format("Copy {0} Related",s.name),ProgressPrimCount,ProgressSecCount);
                if (Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyRelatedProducts before copying Product: {0}, members Count: {1}.",s.name,count),Crm2CrmTrace.Sw.Info);
                for (int i = 0; i < count; i++)
                {
                    ADNDynProduct m                                 =   List[i];
                    string PrimaryFieldStringValue                  =   m.name;
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyRelatedProducts Copy process product: {0}, i: {1}/{2}",PrimaryFieldStringValue, i+1,count), Crm2CrmTrace.Sw.Info);
                    SetUpdateProgress(string.Format("{0} '{1}'",s.name,PrimaryFieldStringValue),ProgressPrimCount,ProgressSecCount++);
                    // filter for already created records
                    ADNDynProduct dynTarget                         =   null;
                    if ( DicDic.ContainsKey(CrmStr.product) && DicDic[CrmStr.product].ContainsKey(m.productid) )
                    {
                        dynTarget                                   =   (ADNDynProduct)DicDic[CrmStr.product][m.productid];
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyRelatedProducts product already retrieved: {0}.",PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                    }
                    else
                    {
                        dynTarget                                   =   (ADNDynProduct)CopyDynEntity(m,TConfDest,null);
                    }
                    // Add target to Kit
                    newAcc.SetRelated(dynTarget,true);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyRelatedProducts added {0}.",PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                }
            }
            catch (InnerException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string msg          =   string.Format("[E]Crm2Crm CopyRelatedProducts ex : {0}", ex);
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                DicErrors.Add(string.Format("Copy CopyRelatedProducts failed for {0}.",s.name));
                throw new InnerException(msg,ex);
            }

            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopySubstitutes END found: {0}", count),Crm2CrmTrace.Sw.Info);
            return count;
        }

        /// <summary>
        /// Copy all the source list members to dest list
        /// Pb : no message operates on ListMemmber
        /// From blog dynamcs ->A Marketing list in CRM, can be a collection accounts or contacts or leads. Retrieving the members of a marketing list is not as as simple. 
        /// We just realized that the list member entity only stores the link to the entity and Retrieve method is not supported by this entity.
        /// Hence to retrieve the list members for a given entity we need to identify the type of entity being supported by the list i.e Leads/Accounts/Contacts 
        /// and then using the link entity functionality link it with the listmember entity to get the list.
        /// </summary>
        int CopyListMembers(ADNDynList s,ADNDynList newAcc)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyListMembers BEG source: {0}, membertype: {1}",s.listname,s.MemberTypename),Crm2CrmTrace.Sw.Info);
            int count                                               =   0;
            try
            {
                string targetEntity                                 =   s.MemberTypename;
                
                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper2,ResetWrapper,targetEntity);
                InternalQueryExpression qe                          =   new InternalQueryExpression();
                qe.EntityName                                       =   targetEntity;
                InternalAllColumns RequestCols                      =   new InternalAllColumns();
                
                // link from customer entity to listmember
                InternalLinkEntity le                               =   new InternalLinkEntity();
                le.LinkFromEntityName                               =   targetEntity;
                le.LinkFromAttributeName                            =   s.MemberLinkKey;
                le.LinkToEntityName                                 =   CrmStr.listmember;
                le.LinkToAttributeName                              =   CrmStr.entityid;

                // link from listmember to list
                InternalLinkEntity le2                              =   new InternalLinkEntity();
                le2.LinkFromEntityName                              =   CrmStr.listmember;
                le2.LinkFromAttributeName                           =   CrmStr.listid;
                le2.LinkToEntityName                                =   CrmStr.list;
                le2.LinkToAttributeName                             =   CrmStr.listid;

                
                InternalFilterExpression fi                         =   new InternalFilterExpression();
                // condition for listid
                InternalConditionExpression ex                      =   new InternalConditionExpression();
                ex.AttributeName                                    =   CrmStr.listid;
                ex.Operator                                         =   InternalConditionOperator.Equal;
                ex.Values                                           =   new string[]{s.listid.ToString()};

                //add condition to linkentity
                le2.LinkCriteria                                    =   fi;
                fi.Conditions                                       =   new InternalConditionExpression[]{ex};

                // chain linkentity2 to linkentity
                le.LinkEntities                                     =   new InternalLinkEntity[]{le2};

                //add linkentities to Query Expression 
                qe.LinkEntities                                     =   new InternalLinkEntity[]{le};
                qe.ColumnSet                                        =   RequestCols;
                
                
                InternalBusinessEntityCollection allEnt             =   allEntQuery.adminRetrieve(qe);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                EntityConfig ListMemberTConfig                      =   new EntityConfig(Wrapper,targetEntity);
                EntityConfig ListMemberTConfig2                     =   new EntityConfig(Wrapper2,targetEntity);
                List<DynEntity> List                                =   new List<DynEntity>();
                // Transform them in DynEntities and insert them in dynEntList
                if ( allEntQuery.RetrievedCount > 0 )
                {
                    // Transform them in DynEntities and insert them in dynEntList
                    Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                        delegate(InternalDynamicEntity de)
                        {
                            DynEntity ob                            =   DynEntity.CreateFromDynamicEntity(Wrapper2,de,_columnDescriptors);
                            ob.EntityMData                          =   ListMemberTConfig2.entityMetaData;
                            _columnDescriptors                      =   ob.PropertyDescriptorCollection;
                            List.Add(ob);
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyListMembers found entity: {0}", ob.PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                            return true; // continue
                        });
                }
                // Duplicate the members
                count                                               =   List.Count;
                ResetProgressSecTotal(count);
                SetUpdateProgress(string.Format("Copy {0} ListMembers",s.name),ProgressPrimCount,ProgressSecCount);
                if (Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyListMembers before copying List: {0}, members Count: {1}.",s.name,count),Crm2CrmTrace.Sw.Info);
                for (int i = 0; i < count; i++)
                {
                    DynEntity m                                     =   List[i];
                    string PrimaryFieldStringValue                  =   m.PrimaryFieldStringValue;
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyListMembers Copy process entity: {0}, i: {1}/{2}",PrimaryFieldStringValue, i+1,count), Crm2CrmTrace.Sw.Info);
                    SetUpdateProgress(string.Format("{0} '{1}'",s.name,PrimaryFieldStringValue),ProgressPrimCount,ProgressSecCount++);
                    // filter for already created records
                    ADNDynCustomer dynTarget                        =   null;
                    if ( DicDic.ContainsKey(targetEntity) && DicDic[targetEntity].ContainsKey(m.PrimaryKeyGuidValue) )
                    {
                        dynTarget                                   =   (ADNDynCustomer)DicDic[targetEntity][m.PrimaryKeyGuidValue];
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyListMembers already created {0}, found: {1}.",targetEntity,PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                    }
                    else
                    {
                        dynTarget                                   =   (ADNDynCustomer)CopyDynEntity(m,ListMemberTConfig,null);
                    }
                    // Add target to dest list
                    newAcc.AddMemberList(dynTarget,true);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyListMembers added {0}.",PrimaryFieldStringValue),Crm2CrmTrace.Sw.Info);
                }
            }
            catch (InnerException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string msg          =   string.Format("[E]Crm2Crm CopyListMembers ex : {0}", ex);
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                DicErrors.Add(string.Format("Copy List Members failed for {0}.",s.listname));
                throw new InnerException(msg,ex);
            }

            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyListMembers END found: {0}", count),Crm2CrmTrace.Sw.Info);
            return count;
        }


        /// <summary>
        /// Replace the various Ids in XML request by new values
        /// </summary>
        string ConvertConstraint(DynEntity s,string Val)
        {
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ConvertConstraint BEG Val: {0}", Val),Crm2CrmTrace.Sw.Info);
            /*
           new System.Text.StringBuilder("<Constraints>");
           builder.Append("<Constraint>");
           builder.Append("<Expression>");
           builder.Append("<Body>resource[\"Id\"] == ");
           builder.Append(user.UserId.ToString("B"));
           builder.Append(" || resource[\"Id\"] == ");
           builder.Append(vanId.ToString("B"));
           builder.Append("</Body>");
           builder.Append("<Parameters>");
           builder.Append("<Parameter name=\"resource\" />");
           builder.Append("</Parameters>");
           builder.Append("</Expression>");
           builder.Append("</Constraint>");
           builder.Append("</Constraints>");
           */
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ConvertConstraint END Val: {0}", Val),Crm2CrmTrace.Sw.Info);
            return Val;
        }

        
        int _EntranceLevel  =   0;
        /// <summary>
        /// Duplicate a source entity in the dest crm
        /// parentLookupName is the PrimaryField value of the Parent when CopyDynEntity is called from RetrieveLookup (we are copying the lookup entity)
        /// parentLookupName is the calling calendarid when calling Duplicate CallendarRule: CopyCalendar->DupRules->RetrieveLookup->CopyCalendar
        /// </summary>
        public DynEntity CopyDynEntity(DynEntity s,EntityConfig TConfDest,object parentLookupName)
        {
            string PrimaryFieldStringValue          =   s.PrimaryFieldStringValue;
            string SchemaName                       =   s.SchemaName;
            Guid PrimaryKeyGuidValue                =   s.PrimaryKeyGuidValue;
            SetUpdateProgress(string.Format("{0} '{1}'",SchemaName,PrimaryFieldStringValue),ProgressPrimCount,ProgressSecCount);
            if (Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity BEG Entity: {0}, PrimaryFieldStringValue: {1}, Re-entranceLevel : {2}, TConfDest.entityName: {3}",
                    new object[]{SchemaName,PrimaryFieldStringValue,_EntranceLevel,TConfDest.entityName}), Crm2CrmTrace.Sw.Info);
            _EntranceLevel++;
            bool isOk                               =   false;
            DynEntity newAcc                        =   null;
            DynEntity dup                           =   null;
            DicDynEnt dic                           =   null;
            if ( !DicDic.ContainsKey(SchemaName) )
            {
                dic                                 =   new DicDynEnt();
                DicDic.Add(SchemaName, dic);
                if ( Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity added Dic for SchemaName: {0}.",SchemaName),Crm2CrmTrace.Sw.Info );
            }
            else 
            {
                dic                                =   DicDic[SchemaName];
                // first check in dic to avoid a calls
                if ( dic.ContainsKey(PrimaryKeyGuidValue) )
                {
                    if ( Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity found in Dic SchemaName: {0}, ID: {1}.",SchemaName,PrimaryKeyGuidValue),Crm2CrmTrace.Sw.Info );
                    newAcc                  =   DicDic[SchemaName][PrimaryKeyGuidValue];
                    _EntranceLevel--;
                    return newAcc;;
                }
            }
            try
            {
                if ( ShoudCheckDuplicates(SchemaName) )
                {
                    if ( SchemaName == CrmStr.discount )
                    {
                        ADNDynDiscount ws           =   (ADNDynDiscount)s;
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity discount parentLookupName: '{0}'.",( parentLookupName == null ) ? "null" : parentLookupName),Crm2CrmTrace.Sw.Info);
                        // we try to get the 'parent' name from source record
                        if ( parentLookupName == null )
                        {
                            ADNDynDiscountType ds   =   new ADNDynDiscountType(Wrapper2,ws.discounttypeid);
                            ds.EntityID = ws.discounttypeid;
                            if ( ds.adminRetrieve() )
                            {
                                parentLookupName    =   ds.name;
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity discount parentLookupName from copied discount: '{0}'.",parentLookupName),Crm2CrmTrace.Sw.Info);
                            }
                        }
                        ADNDynDiscount newWs        =   null;
                        try
                        {
                            newWs                   =   Wrapper.Util.FindDiscount(ws.isamounttype,ws.lowquantity,ws.highquantity,ws.percentage,ws.amount,(string)parentLookupName);
                            dup                     =   newWs;
                        }
                        catch ( Exception ex )
                        {
                            if ( Crm2CrmTrace.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm CopyDynEntity FindDiscount ex: {0}.",ex),Crm2CrmTrace.Sw.Info);
                        }
                        if ( newWs != null )
                        {
                            DupCount++;
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity discount found for parent: '{0}'.",parentLookupName),Crm2CrmTrace.Sw.Info);
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity discount found Entity: {0}, PrimaryFieldStringValue: {1}, ShouldUpdate: {2}, dup.modifiedOn: {3}, source.modifiedOn: {4}",
                                    new object[]{SchemaName,PrimaryFieldStringValue,ShouldUpdate,
                                        dup.ContainsKey(CrmStr.modifiedon) ? dup.modifiedon:"No ModifiedOn",
                                        s.ContainsKey(CrmStr.modifiedon) ? s.modifiedon:"No ModifiedOn"}) ,Crm2CrmTrace.Sw.Info);
                            if ( !ShouldUpdate || (dup.ContainsKey(CrmStr.modifiedon) && s.ContainsKey(CrmStr.modifiedon) && (dup.modifiedonLocalDate >= s.modifiedonLocalDate )) ) // we keep duplicates with modified value equal or more recent than org
                            {
                                _EntranceLevel--;
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity END discount duplicate found Entity: {0}, PrimaryFieldStringValue: {1}, Re-entranceLevel : {2}",
                                        SchemaName,PrimaryFieldStringValue,_EntranceLevel),Crm2CrmTrace.Sw.Info);
                                return newWs;
                            }
                        }
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity discount NOT found or older for parent: '{0}' duplicating/updating.",parentLookupName),Crm2CrmTrace.Sw.Info);
                    }
                    else if ( SchemaName == CrmStr.relationshiprolemap )
                    {
                    }
                    else
                    {
                        string PrimaryFieldName         =   s.PrimaryFieldName;
                        // need to call, but when primaryfield exist (all system tables like productpricelevel as no primaryfield, so we don't check for dup values
                        if ( !s.HasPrimaryField )
                        {
                            if ( ExistNPRimaryFieldDuplicates(SchemaName,s,ref dup) )
                            {
                                DupCount++;
                                if ( !dic.ContainsKey(PrimaryKeyGuidValue) )
                                    dic.Add(PrimaryKeyGuidValue,dup);
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity duplicate found Entity: {0}, PrimaryFieldStringValue: {1}, ShouldUpdate: {2}, dup.modifiedOn: {3}, source.modifiedOn: {4}",
                                        new object[]{SchemaName,PrimaryFieldStringValue,ShouldUpdate,
                                            dup.ContainsKey(CrmStr.modifiedon) ? dup.modifiedon:"No ModifiedOn",
                                            s.ContainsKey(CrmStr.modifiedon) ? s.modifiedon:"No ModifiedOn"}) ,Crm2CrmTrace.Sw.Info);
                                if ( !ShouldUpdate || (dup.ContainsKey(CrmStr.modifiedon) && s.ContainsKey(CrmStr.modifiedon) && (dup.modifiedonLocalDate >= s.modifiedonLocalDate )) ) // we keep duplicates with modified value equal or more recent than org
                                {
                                    _EntranceLevel--;
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity END duplicate found Entity: {0}, PrimaryKeyGuidValue: {1}, Re-entranceLevel : {2}",
                                            SchemaName,PrimaryKeyGuidValue,_EntranceLevel),Crm2CrmTrace.Sw.Info);
                                    return dup;
                                }
                            }
                        }
                        else 
                        {
                            if ( !string.IsNullOrEmpty(PrimaryFieldStringValue) )
                            {
                                if ( ExistDuplicates(s,PrimaryFieldStringValue,ref dup) )
                                {
                                    DupCount++;
                                    if ( !dic.ContainsKey(PrimaryKeyGuidValue) )
                                        dic.Add(PrimaryKeyGuidValue,dup);
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity duplicate found Entity: {0}, PrimaryFieldStringValue: {1}, ShouldUpdate: {2}, dup.modifiedOn: {3}, source.modifiedOn: {4}",
                                            new object[]{SchemaName,PrimaryFieldStringValue,ShouldUpdate,
                                                dup.ContainsKey(CrmStr.modifiedon) ? dup.modifiedon:"No ModifiedOn",
                                                s.ContainsKey(CrmStr.modifiedon) ? s.modifiedon:"No ModifiedOn"}),Crm2CrmTrace.Sw.Info);
                                    if ( !ShouldUpdate || ( dup.ContainsKey(CrmStr.modifiedon) && s.ContainsKey(CrmStr.modifiedon) && ( dup.modifiedonLocalDate >= s.modifiedonLocalDate ) ) ) // we keep duplicates with modified value equal or more recent than org
                                    {
                                        _EntranceLevel--;
                                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                                            Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity END duplicate found Entity: {0}, PrimaryFieldStringValue: {1}, Re-entranceLevel : {2}",
                                                SchemaName,PrimaryFieldStringValue,_EntranceLevel),Crm2CrmTrace.Sw.Info);
                                        return dup;
                                    }
                                }
                            }
                            else
                            {
                                string searchField1     =   string.Empty;
                                string searchVal1       =   string.Empty;
                                string searchField2     =   string.Empty;
                                string searchVal2       =   string.Empty;
                                // Let try with all activities
                                if ( s.ContainsKey(CrmStr.description) && s.ContainsKey(CrmStr.regardingobjectid) )
                                {
                                    string lookupType   =   s.LookupPropertyType(CrmStr.regardingobjectid);
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity lookupType: {0}.",lookupType),Crm2CrmTrace.Sw.Info);
                                    if ( DicDic.ContainsKey(lookupType) && DicDic[lookupType].ContainsKey(s.LookupPropertyValue(CrmStr.regardingobjectid)) )
                                    {
                                        searchField1    =   CrmStr.description;
                                        searchField2    =   CrmStr.regardingobjectid;
                                        searchVal2      =   DicDic[lookupType][s.LookupPropertyValue(CrmStr.regardingobjectid)].PrimaryKeyGuidValue.ToString();
                                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                                            Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity searchVal2: {0}.",searchVal2),Crm2CrmTrace.Sw.Info);
                                    }
                                }
                                // Calendar often empty name, try with description and user
                                else if ( SchemaName == CrmStr.calendar )
                                {
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity calendar ContainsKey(CrmStr.description): {0}, ContainsKey(CrmStr.primaryuserid): {1}.",s.ContainsKey(CrmStr.description),s.ContainsKey(CrmStr.primaryuserid)),Crm2CrmTrace.Sw.Info);
                                    if ( s.ContainsKey(CrmStr.primaryuserid) )
                                    {
                                        if ( s.ContainsKey(CrmStr.description)  )
                                        {
                                            Guid primUserId       =   s.UniqueIdentifierPropertyValue(CrmStr.primaryuserid);
                                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity primaryuserid: {0}.",primUserId),Crm2CrmTrace.Sw.Info);
                                            if ( DicDic[CrmStr.systemuser].ContainsKey(primUserId) )
                                            {
                                                searchField1 = CrmStr.description;
                                                searchField2 = CrmStr.primaryuserid;
                                                searchVal2 = DicDic[CrmStr.systemuser][primUserId].PrimaryKeyGuidValue.ToString();
                                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity searchVal2: {0}.",searchVal2),Crm2CrmTrace.Sw.Info);
                                            }
                                        }
                                        else
                                        {
                                            Guid primUserId       =   s.UniqueIdentifierPropertyValue(CrmStr.primaryuserid);
                                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity primaryuserid: {0}.",primUserId),Crm2CrmTrace.Sw.Info);
                                            if ( DicDic[CrmStr.systemuser].ContainsKey(primUserId) )
                                            {
                                                searchField1    =   CrmStr.primaryuserid;
                                                searchVal1      =   DicDic[CrmStr.systemuser][primUserId].PrimaryKeyGuidValue.ToString();
                                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity searchVal1: {0}.",searchVal1),Crm2CrmTrace.Sw.Info);
                                            }
                                        }
                                    }
                                }
                                // We get something to search for
                                if ( ( ( searchVal2 != string.Empty ) && ExistDuplicatesExt(s,searchField1,searchField2,searchVal2,ref dup) )
                                    || ( ( searchVal1 != string.Empty ) && ExistDuplicates1Factor(s,searchField1,searchVal1,ref dup) ) )
                                {
                                    DupCount++;
                                    if ( !dic.ContainsKey(PrimaryKeyGuidValue) )
                                        dic.Add(PrimaryKeyGuidValue,dup);
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity duplicateExt found Entity: {0}, PrimaryFieldStringValue: {1}, ShouldUpdate: {2}, dup.modifiedOn: {3}, source.modifiedOn: {4}",
                                            new object[]{SchemaName,PrimaryFieldStringValue,ShouldUpdate,
                                                dup.ContainsKey(CrmStr.modifiedon) ? dup.modifiedon:"No ModifiedOn",
                                                s.ContainsKey(CrmStr.modifiedon) ? s.modifiedon:"No ModifiedOn"}),Crm2CrmTrace.Sw.Info);
                                    if ( !ShouldUpdate || ( dup.ContainsKey(CrmStr.modifiedon) && s.ContainsKey(CrmStr.modifiedon) && ( dup.modifiedonLocalDate >= s.modifiedonLocalDate ) ) ) // we keep duplicates with modified value equal or more recent than org
                                    {
                                        _EntranceLevel--;
                                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                                            Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity END duplicate found Entity: {0}, PrimaryFieldStringValue: {1}, Re-entranceLevel : {2}",
                                                SchemaName,PrimaryFieldStringValue,_EntranceLevel),Crm2CrmTrace.Sw.Info);
                                        return dup;
                                    }
                                }
                            }
                        }
                    }
                }

                // at that time no duplicates found for entities with a PrimaryField ->need to create
                // for entities without PrimaryField we could check after recovering all lookup wich could lead to a duplicate create condition
                switch ( SchemaName )
                {
                    case CrmStr.account:
                    newAcc                                      =   new ADNDynAccount(Wrapper,s.name);
                    break;
                    case CrmStr.contact:
                    newAcc                                      =   new ADNDynContact(Wrapper,s.StringPropertyValue(CrmStr.firstname),s.StringPropertyValue(CrmStr.lastname));
                    break;
                    case CrmStr.lead:
                    newAcc                                      =   new ADNDynLead(Wrapper,s.StringPropertyValue(CrmStr.firstname),s.StringPropertyValue(CrmStr.lastname));
                    break;
                    case CrmStr.discount:
                    newAcc                                      =   new ADNDynDiscount(Wrapper);
                    break;
                    case CrmStr.product:
                    newAcc                                      =   new ADNDynProduct(Wrapper,s.PrimaryFieldStringValue);
                    break;
                    default:
                    newAcc                                      =   DynEntity.CreateEmptyDynamicEntity(Wrapper,SchemaName);
                    break;
                }
                string stateCode                                =   string.Empty;
                int statusCode                                  =   -1; // if status is not present -1 will set te default value (sdk)
                InternalDynamicEntityArray calendarrules        =   null;
                bool isBaseUnit                                 =   false;
                DynEntity DynBaseUomSchedule                    =   null;
                List<DynEntity> CalendarRulesLst                =   null;
                Guid PricelevelId                               =   Guid.Empty;
                bool NeedUpdateAfterCreate                      =   false;
                byte[] data                                     =   null; // for annotations
                // Duplicate the attributes of source entity
                s.wrapper.Util.ExecForEachDynamicEntityProperty(s,
                    delegate(string Name,object Val,object val2,object val3,AttributeInternalType tp)
                    {
                        if ( !TConfDest.attributesDic.ContainsKey(Name) )
                        {
                            if ( Crm2CrmTrace.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm CopyDynEntity Property not in V4 Name: {0}",Name),Crm2CrmTrace.Sw.Info);
                            if ( Name != CrmStr.calendarrules )
                                return true;
                        }
                        InternalAttributeMetadata attributeMetaData =   null;
                        bool ValidForCreate                         =   false;
                        bool ValidForUpdate                         =   false;
                        if ( Name != CrmStr.calendarrules )
                        {
                            attributeMetaData                       =   TConfDest[Name];
                            ValidForCreate                          =   Wrapper.Util.ExtractAttributeFieldAsBool(attributeMetaData,InternalAttributeFields.ValidForCreate);
                            ValidForUpdate                          =   Wrapper.Util.ExtractAttributeFieldAsBool(attributeMetaData,InternalAttributeFields.ValidForUpdate);
                        }
                        else
                        {
                            calendarrules                           =   (InternalDynamicEntityArray)Val;
                            ValidForCreate                          =   true; //test
                        }
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Name: {0}, ValidForCreate: {1}, ValidForUpdate: {2}, AttributeInternalType: {3}.",
                                new object[]{Name,ValidForCreate,ValidForUpdate,tp}),Crm2CrmTrace.Sw.Info);
                        if ( !ValidForCreate )
                        {
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Not Valid For Create Name: {0}",Name),Crm2CrmTrace.Sw.Info);
                            if ( Name.Equals(CrmStr.statecode) )
                            {
                                stateCode                           =   (string)Val;
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity stateCode for {0}: {1}",SchemaName,Val),Crm2CrmTrace.Sw.Info);
                            }
                            else if ( Name.Equals(CrmStr.isschedulebaseuom) )
                            {
                                isBaseUnit                          =   (bool)Val;
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity isschedulebaseuom for {0}: {1}",SchemaName,Val),Crm2CrmTrace.Sw.Info);
                            }
                            else if ( Name.Equals(CrmStr.pricelevelid) ) // we must first create product, then add the default pricelevel
                            {
                                PricelevelId                        =   (Guid)Val;
                                NeedUpdateAfterCreate               =   true;
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity PricelevelId for {0}: {1}",SchemaName,Val),Crm2CrmTrace.Sw.Info);
                            }
                            return true;
                        }
                        switch ( tp )
                        {
                            case AttributeInternalType.Float:
                            if ( Val is double )
                                newAcc.AddFloatProperty(Name,(double)Val);
                            else
                                newAcc.AddFloatProperty(Name,(float)Val);
                            break;
                            case AttributeInternalType.Integer:
                            newAcc.AddNumberProperty(Name,(int)Val);
                            break;
                            case AttributeInternalType.Status:
                            if ( Name.Equals(CrmStr.statuscode) )
                            {
                                statusCode                          =   (int)Val;
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity statuscode for {0}: {1}",SchemaName,Val),Crm2CrmTrace.Sw.Info);
                            }
                            else
                                newAcc.AddStatusProperty(Name,(int)Val);
                            break;
                            case AttributeInternalType.Picklist:
                            newAcc.AddPicklistProperty(Name,(int)Val);
                            break;
                            case AttributeInternalType.Decimal:
                            newAcc.AddDecimalProperty(Name,(decimal)Val);
                            break;
                            case AttributeInternalType.State:
                            if ( Name.Equals(CrmStr.statecode) )
                            {
                                stateCode                           =   (string)Val;
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity stateCode for {0}: {1}",SchemaName,Val),Crm2CrmTrace.Sw.Info);
                            }
                            break;
                            case AttributeInternalType.String:
                            if ( ( Name == CrmStr.quotenumber ) && ( SchemaName == CrmStr.quote ) ) // Pb with quote numbers, can't keep them, diplicate risk
                                break;
                            if ( ( Name == CrmStr.constraints ) && ( ( SchemaName == CrmStr.constraintbasedgroup ) || ( SchemaName == CrmStr.resourcespec ) ) )
                                Val = ConvertConstraint(s,(string)Val);
                            newAcc.AddStringProperty(Name,(string)Val);
                            break;
                            case AttributeInternalType.Memo:
                            newAcc.AddStringProperty(Name,(string)Val);
                            break;
                            case AttributeInternalType.DateTime:
                            newAcc.AddDateTimeProperty(Name,(string)Val);
                            break;
                            case AttributeInternalType.Money:
                            newAcc.AddMoneyProperty(Name,(decimal)Val);
                            break;
                            case AttributeInternalType.Boolean:
                            newAcc.AddBooleanProperty(Name,(bool)Val);
                            break;
                            case AttributeInternalType.PrimaryKey:
                            break;
                            case AttributeInternalType.UniqueIdentifier:
                            switch ( SchemaName )
                            {
                                case CrmStr.salesliteratureitem:
                                if ( Name == CrmStr.organizationid )
                                {
                                    FindUniqueIdentifier(newAcc,Name,CrmStr.organization,(Guid)Val);
                                }
                                break;
                                case CrmStr.productassociation:
                                if ( Name == CrmStr.associatedproduct || Name == CrmStr.productid )
                                {
                                    FindUniqueIdentifier(newAcc,Name,CrmStr.product,(Guid)Val);
                                }
                                break;
                                case CrmStr.productsalesliterature:
                                if ( Name == CrmStr.productid )
                                {
                                    FindUniqueIdentifier(newAcc,Name,CrmStr.product,(Guid)Val);
                                }
                                else if ( Name == CrmStr.salesliteratureid )
                                {
                                    FindUniqueIdentifier(newAcc,Name,CrmStr.salesliterature,(Guid)Val);
                                }
                                break;
                                case CrmStr.productsubstitute:
                                if ( Name == CrmStr.substitutedproductid || Name == CrmStr.productid )
                                {
                                    FindUniqueIdentifier(newAcc,Name,CrmStr.product,(Guid)Val);
                                }
                                break;
                            }
                            break;
                            case AttributeInternalType.CalendarRules:
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine("[V]Crm2Crm CopyDynEntity calling DuplicateCalendarRules.",Crm2CrmTrace.Sw.Info);
                            CalendarRulesLst                    =   DuplicateCalendarRules(s,newAcc,Name,(InternalDynamicEntityArray)Val);
                            break;
                            case AttributeInternalType.PartyList:
                            DuplicatePartyList(newAcc,Name,(InternalDynamicEntityArray)Val);
                            break;
                            case AttributeInternalType.Lookup:
                            // avoid pb in serviceappointment
                            if ( Name == CrmStr.businessunit )
                            {
                                if ( ( (string)val3 ).Equals(Wrapper2.OrganizationName) )
                                {
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity businessunit changed from '{0}' to '{1}'",val3,Wrapper.OrganizationName),Crm2CrmTrace.Sw.Info);
                                    val3                        =   Wrapper.OrganizationName;
                                }
                            }
                            else if ( SchemaName == CrmStr.customerrelationship && Name == CrmStr.converserelationshipid )
                            {
                                bool contain                    =   RelationShipDic.ContainsKey((Guid)Val);
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Lookup converserelationshipid Previouslookup found: {0}, _EntranceLevel: {1}",contain,_EntranceLevel),Crm2CrmTrace.Sw.Info);
                                if ( contain )
                                {
                                    // caller is the Lookup value, but it is not created, so we will need to update this reation after caller creation
                                    // we need to set this lookup after caller create
                                    if ( !Lookup2Set.ContainsKey(Name) )
                                        Lookup2Set.Add(Name,newAcc);
                                    RelationShipDic.Clear();
                                    break;// DO NOT CALL retrievelookup or infinite loop
                                }
                                Guid orgGuid                    =   s.PrimaryKeyGuidValue;
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Lookup converserelationshipid storing Guid: {0}, _EntranceLevel: {1}",orgGuid,_EntranceLevel),Crm2CrmTrace.Sw.Info);
                                // we store this under its own key to avoid reentrancy
                                if ( !RelationShipDic.ContainsKey(orgGuid) )
                                    RelationShipDic.Add(orgGuid,newAcc);
                                NeedUpdateAfterCreate           =   true; // we will have to update the corresponding relationship record as it will be created without the lookup value
                            }
                            else if ( SchemaName == CrmStr.calendarrule ) // also avoid infinie loop
                            {
                                Guid orgcalendarID              =   (Guid)parentLookupName;
                                Guid calendarID                 =   (Guid)Val;
                                bool contain                    =   DicDic.ContainsKey(CrmStr.calendar) && DicDic[CrmStr.calendar].ContainsKey(calendarID);
                                bool equalOld                   =   ( orgcalendarID == calendarID);
                                if ( contain ) // no need to retirve already there
                                {
                                    newAcc.AddLookupProperty(Name,CrmStr.calendar,DicDic[CrmStr.calendar][(Guid)Val].PrimaryKeyGuidValue);
                                    break;
                                }
                                if ( ( Name == CrmStr.calendarid ) && equalOld ) // also avoid infinie loop calendar->rule->calendar
                                {
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Lookup calendarid Previouslookup found in dic: {0}, Equal caller callendar: {1} _EntranceLevel: {2}",
                                            contain,equalOld ,_EntranceLevel),Crm2CrmTrace.Sw.Info);
                                    // temporarly we set the source value, must be reset before create and updated after with new calendarid
                                    newAcc.AddLookupProperty(CrmStr.calendarid,CrmStr.calendar,orgcalendarID);
                                    break;
                                }
                                // else lets retrieve this calendar lookup
                            }
                            /*
                        else if ( SchemaName == CrmStr.service && ((Name == CrmStr.resourcespecid) || (Name == CrmStr.strategyid) ) )
                        {
                            // we don't know how to create them so try without them ....
                            break;
                        }*/
                            else if ( SchemaName == CrmStr.relationshiprolemap ) // try to optimze with fixed entities lookup
                            {
                                if ( Name == CrmStr.relationshiproleid )
                                    val2                        =   CrmStr.relationshiprole;
                            }
                            DynEntity lkDyn                     =    RetrieveLookup(newAcc,Name,(Guid)Val,val3,PrimaryFieldStringValue,val2);
                            if ( ( lkDyn != null ) && ( SchemaName == CrmStr.uom ) && ( Name == CrmStr.uomscheduleid )  )
                            {
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity DynBaseUomSchedule set: '{0}'",lkDyn.PrimaryKeyGuidValue),Crm2CrmTrace.Sw.Info);
                                DynBaseUomSchedule              =   lkDyn;
                            }
                            break;
                            case AttributeInternalType.Customer:
                            RetrieveCustomer(newAcc,Name,(Guid)Val,val2,val3);
                            break;
                            case AttributeInternalType.EntityNameReference:
                            newAcc.AddEntityNameReferenceProperty(Name,(string)Val);
                            break;
                            case AttributeInternalType.Owner:
                            {
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Owner Type: '{0}'",val2),Crm2CrmTrace.Sw.Info);
                                string otp                      =   (string)val2;
                                FindOwner(otp,Name,newAcc,(Guid)Val,(string)val3);
                            }
                            break;
                            default:
                            if ( Crm2CrmTrace.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm CopyDynEntity missing column: [{0}], type: '{1}'.",Name,tp),Crm2CrmTrace.Sw.Info);
                            break;
                        }
                        return true;
                    }
                    );

                if ( Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity after copying properties dup null: {0}",(dup == null)),Crm2CrmTrace.Sw.Info);
                // V3/V4 incompatibility and special processings before create 
                if ( SchemaName == CrmStr.uomschedule )
                {
                    if ( newAcc.StringPropertyValue(CrmStr.baseuomname) == string.Empty )
                    {
                        string baseuomname                      =   "Crm2Crm base uom";
                        if ( parentLookupName != null && ( parentLookupName is string ) )
                            baseuomname                         =   (string)parentLookupName;
                        newAcc.AddStringProperty(CrmStr.baseuomname,baseuomname);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Added baseuomname: {0}.",baseuomname),Crm2CrmTrace.Sw.Info);
                    }
                }
                else if ( SchemaName == CrmStr.annotation )
                {
                    bool isDocument                     =   false;
                    if ( s.dicProperty.ContainsKey(CrmStr.isdocument) )
                        isDocument                      =   s.BooleanPropertyValue(CrmStr.isdocument);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity annotation isDocument: {0}.",isDocument),Crm2CrmTrace.Sw.Info);
                    if ( isDocument )
                    {
                        Guid annotationId               =   s.KeyPropertyValue(CrmStr.annotationid);
                        string attachid                 =   annotationId.ToString();
                        int objectTpCode                =   (int)CRMUtil.typeCode(s.SchemaName);
                        string filename                 =   s.StringPropertyValue(CrmStr.filename);
                        int filsize                     =   s.NumberPropertyValue(CrmStr.filesize);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity annotation attachid: {0}, objecttypecode: {1}, filename: {2}, fileSize: {3}.",
                                new object[] { attachid,objectTpCode,filename,filsize }),Crm2CrmTrace.Sw.Info);
                        string url                      =   string.Format("{0}/Activities/Attachment/download.aspx?AttachmentType=5&AttachmentId={{{1}}}",
                                                                    Wrapper2.DownloadServerUrl,attachid);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity annotation Url: {0}.",url),Crm2CrmTrace.Sw.Info);
                        bool OkDownload                 =   false;
                        data                            =   DownLoadFile(url,ref OkDownload);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity annotation/attachment download Ok: {0}, File: {1}.",
                                OkDownload,filename),Crm2CrmTrace.Sw.Info);
                        if ( OkDownload )
                        {
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity annotation data.Length: {0}.",data.Length),Crm2CrmTrace.Sw.Info);
                            string b64                  =   Convert.ToBase64String(data);
                            newAcc.AddStringProperty(CrmStr.documentbody,b64);
                        }
                    }
                }
                else if ( SchemaName == CrmStr.salesliteratureitem )
                {
                    Guid Id                             =   s.KeyPropertyValue(CrmStr.salesliteratureitemid);
                    string strId                        =   Id.ToString();
                    int objectTpCode                    =   (int)CRMUtil.typeCode(s.SchemaName);
                    string filename                     =   s.StringPropertyValue(CrmStr.filename);
                    int filsize                         =   s.NumberPropertyValue(CrmStr.filesize);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity salesliteratureitem id: {0}, objecttypecode: {1}, filename: {2}, fileSize: {3}.",
                            new object[] { strId,objectTpCode,filename,filsize }),Crm2CrmTrace.Sw.Info);
                    string url                          =   string.Format("{0}/Activities/Attachment/download.aspx?AttachmentType={1}&AttachmentId={{{2}}}",
                                                                Wrapper2.DownloadServerUrl,objectTpCode,strId);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity salesliteratureitem Url: {0}.",url),Crm2CrmTrace.Sw.Info);
                    bool OkDownload                     =   false;
                    data                                =   DownLoadFile(url,ref OkDownload);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity salesliteratureitem download Ok: {0}, File: {1}.",
                            OkDownload,filename),Crm2CrmTrace.Sw.Info);
                    if ( OkDownload )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity annotation data.Length: {0}.",data.Length),Crm2CrmTrace.Sw.Info);
                        string b64                      =   Convert.ToBase64String(data);
                        newAcc.AddStringProperty(CrmStr.documentbody,b64);
                    }
                }
                else if ( SchemaName == CrmStr.calendar )
                {
                    if ( ( CalendarRulesLst != null ) && ( CalendarRulesLst.Count > 0 ) )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity checking calendarrules count: {0}",CalendarRulesLst.Count),Crm2CrmTrace.Sw.Info);
                        bool shoudlupd              =   false;
                        foreach ( DynEntity dyncal in CalendarRulesLst )
                        {
                            bool contcalend         =   dyncal.ContainsKey(CrmStr.calendarid);
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Updating calendarrules ContainsKey: {0}, calendarid: {1},newPrimaryKeyValue: {2}",
                                    contcalend,(contcalend)? dyncal.LookupPropertyValue(CrmStr.calendarid):Guid.Empty,s.PrimaryKeyGuidValue),Crm2CrmTrace.Sw.Info);
                            if ( contcalend && dyncal.LookupPropertyValue(CrmStr.calendarid) == s.PrimaryKeyGuidValue )
                            {
                                shoudlupd              =   true;
                                break;
                            }
                        }
                        // We must not include the rules in this calendar because we need the calendarid
                        if ( shoudlupd )
                        {
                            NeedUpdateAfterCreate       =   true;
                            newAcc.dicProperty.Remove(CrmStr.calendarrules);
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine("[V]Crm2Crm CopyDynEntity calendar removing calendarrules before create",Crm2CrmTrace.Sw.Info);
                        }
                    }
                }

                // Create the copied entity
                Guid newPrimaryKeyValue                     =   Guid.Empty;
                if ( SchemaName == CrmStr.uom )
                {
                    // We have created the uomschedule and its associated baseoum have been created automatically with quantity=1
                    // we must retrieve it using its name and not try to created the current uom 
                    if ( isBaseUnit )
                    {
                        string baseUom                      =   PrimaryFieldStringValue;
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity uom DynBaseUomSchedule == null: {0}",( DynBaseUomSchedule == null )),Crm2CrmTrace.Sw.Info);
                        if ( DynBaseUomSchedule != null )
                        {
                            // Bug: baseuomname seems to be always null
                            // we need to search for the real base unit
                            InternalQueryExpression qe      =   new InternalQueryExpression();
                            qe.EntityName                   =   CrmStr.uom;
                            InternalAllColumns RequestCols  =   new InternalAllColumns();
                            InternalFilterExpression fi     =   new InternalFilterExpression();
                            InternalConditionExpression ex  =   new InternalConditionExpression();
                            ex.AttributeName                =   CrmStr.uomscheduleid;
                            ex.Operator                     =   InternalConditionOperator.Equal;
                            ex.Values                       =   new string[] { DynBaseUomSchedule.PrimaryKeyGuidValue.ToString() };
                            InternalConditionExpression ex1 =   new InternalConditionExpression();
                            ex1.AttributeName               =   CrmStr.isschedulebaseuom;
                            ex1.Operator                    =   InternalConditionOperator.Equal;
                            ex1.Values                      =   new string[] { "true" };
                            fi.Conditions                   =   new InternalConditionExpression[] { ex,ex1 };
                            qe.ColumnSet                    =   RequestCols;
                            qe.Criteria                     =   fi;
                            int cntf                        =   0;
                            newAcc                          =   Wrapper.Util.FindEntityByQuery<ADNDynUom>(CrmStr.uom,qe,ResetWrapper,ref cntf,!TakeFirstDuplicateEvenIfMore,null); // take when only one
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity found uom name: {0}, cnt: {1}",
                                    (newAcc ==null) ? "Not found":((ADNDynUom)newAcc).name,cntf),Crm2CrmTrace.Sw.Info);
                            if ( newAcc != null ) 
                                newPrimaryKeyValue          =   newAcc.PrimaryKeyGuidValue;
                        }
                        else
                        {
                            bool created                    =   false;
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity uom is base trying to retrieve PrimaryFieldName: {0}, baseuom: {1}",
                                    PrimaryFieldStringValue,baseUom),Crm2CrmTrace.Sw.Info);
                            newAcc                          =   Wrapper.Util.FindEntityByStringField(CrmStr.uom,CrmStr.name,baseUom,false,ref created);
                            if ( newAcc != null ) 
                                newPrimaryKeyValue          =   newAcc.PrimaryKeyGuidValue;
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity base unit found= {0} with name: {1}",( newAcc != null ),baseUom),Crm2CrmTrace.Sw.Info);
                        }
                    }
                    else
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine("[V]Crm2Crm CopyDynEntity uom is not BaseUnit creating.",Crm2CrmTrace.Sw.Info);
                        newPrimaryKeyValue              =   newAcc.adminCreate();
                        CreateCount++;
                    }
                }
                else if ( SchemaName == CrmStr.relationshiprolemap ) ///need to check duplicates with the lookup
                {
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]Crm2Crm CopyDynEntity relationshiprolemap checking duplicate before create.",Crm2CrmTrace.Sw.Info);
                    string associateobjecttypecode      =   newAcc.EntityNameReferencePropertyValue(CrmStr.associateobjecttypecode);
                    string primaryobjecttypecode        =   newAcc.EntityNameReferencePropertyValue(CrmStr.primaryobjecttypecode);
                    Guid relationshiproleid             =   newAcc.LookupPropertyValue(CrmStr.relationshiproleid);
                    DynEntity newDyn                    =   null;
                    if ( ExistRelationshipRoleMapDuplicates(associateobjecttypecode,primaryobjecttypecode,relationshiproleid,ref newDyn) )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine("[V]Crm2Crm CopyDynEntity relationshiprolemap found before create.",Crm2CrmTrace.Sw.Info);
                        newAcc                          =   newDyn;
                        newPrimaryKeyValue              =   newAcc.PrimaryKeyGuidValue;
                        DupCount++;
                    }
                    else
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine("[V]Crm2Crm CopyDynEntity creating relationshiprolemap.",Crm2CrmTrace.Sw.Info);
                        newPrimaryKeyValue              =   newAcc.adminCreate();
                        CreateCount++;
                    }
                }
                else if ( SchemaName == CrmStr.customerrelationship ) ///need to check duplicates with the lookup
                {
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine("[V]Crm2Crm CopyDynEntity customerrelationship checking duplicate before create.",Crm2CrmTrace.Sw.Info);
                    Guid customerid                     =   newAcc.CustomerPropertyValue(CrmStr.customerid);
                    Guid customerroleid                 =   newAcc.LookupPropertyValue(CrmStr.customerroleid);
                    Guid partnerid                      =   newAcc.CustomerPropertyValue(CrmStr.partnerid);
                    Guid partnerroleid                  =   newAcc.LookupPropertyValue(CrmStr.partnerroleid);
                    DynEntity newDyn                    =   null;
                    if ( ExistCustomerRelationshipDuplicates(customerid,customerroleid,partnerid,partnerroleid,ref newDyn) )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine("[V]Crm2Crm CopyDynEntity customerrelationship found before create.",Crm2CrmTrace.Sw.Info);
                        newAcc                          =   newDyn;
                        newPrimaryKeyValue              =   newAcc.PrimaryKeyGuidValue;
                        DupCount++;
                    }
                    else
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine("[V]Crm2Crm CopyDynEntity creating customerrelationship.",Crm2CrmTrace.Sw.Info);
                        newPrimaryKeyValue              =   newAcc.adminCreate();
                        CreateCount++;
                    }
                }
                else if ( SchemaName == CrmStr.calendarrule )
                {
                    newAcc.PrimaryKeyGuidValue          =   Guid.NewGuid();
                    // no create for them we return the entity as this, it will be used in an array of aclendarrules inside calendar entity
                }
                else
                {
                    if ( dup == null )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine("[V]Crm2Crm CopyDynEntity before create.",Crm2CrmTrace.Sw.Info);
                        newPrimaryKeyValue              =   newAcc.adminCreate();
                        CreateCount++;
                    }
                    else
                    {
                        newAcc.PrimaryKeyGuidValue      =   dup.PrimaryKeyGuidValue;
                        newPrimaryKeyValue              =   dup.PrimaryKeyGuidValue;
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine("[V]Crm2Crm CopyDynEntity before update.",Crm2CrmTrace.Sw.Info);
                        newAcc.adminUpdate();
                        UpdateCount++;
                    }
                }
                if ( Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Create Success for Entity: [{0}], CrmId: {1}, stateCode: '{2}'",
                        SchemaName,newPrimaryKeyValue,stateCode),Crm2CrmTrace.Sw.Info);
                isOk                                    =   true;
                if ( Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity NeedUpdateAfterCreate: {0}",NeedUpdateAfterCreate),Crm2CrmTrace.Sw.Info);
                if ( NeedUpdateAfterCreate )
                {
                    switch ( SchemaName )
                    {
                        case CrmStr.calendar:
                        {
                            if ( ( CalendarRulesLst != null ) && ( CalendarRulesLst.Count > 0 ) )
                            {
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Updating calendarrules count: {0}",CalendarRulesLst.Count),Crm2CrmTrace.Sw.Info);
                                bool shoudlupd              =   false;
                                foreach ( DynEntity dyncal in CalendarRulesLst )
                                {
                                    bool contcalend         =   dyncal.ContainsKey(CrmStr.calendarid);
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Updating calendarrules ContainsKey: {0}, calendarid: {1},newPrimaryKeyValue: {2}",
                                            contcalend,(contcalend)? dyncal.LookupPropertyValue(CrmStr.calendarid):Guid.Empty,s.PrimaryKeyGuidValue),Crm2CrmTrace.Sw.Info);
                                    if ( contcalend && dyncal.LookupPropertyValue(CrmStr.calendarid) == s.PrimaryKeyGuidValue )
                                    {
                                        dyncal.AddLookupProperty(CrmStr.calendarid,CrmStr.calendar,newPrimaryKeyValue);
                                        shoudlupd              =   true;
                                    }
                                }
                                if ( shoudlupd )
                                {
                                    InternalDynamicEntityArray newArray = Wrapper.Util.MakeDynamicArray(CalendarRulesLst);
                                    newAcc.AddDynamicEntityArrayProperty(CrmStr.calendarrules,newArray);
                                    newAcc.adminUpdate();
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Updated calendarrules for calendarid: {0}",newPrimaryKeyValue),Crm2CrmTrace.Sw.Info);
                                }
                            }
                        }
                        break;
                        case CrmStr.product:
                        {
                            if ( PricelevelId != Guid.Empty )
                            {
                                RetrieveLookup(newAcc,CrmStr.pricelevelid,PricelevelId,null,PrimaryFieldStringValue,CrmStr.pricelevel);
                                bool retupd             =   false;
                                try
                                {
                                    newAcc.adminUpdate();
                                    retupd              =   true;
                                }
                                catch ( Exception ex )
                                {
                                    if ( Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm CopyDynEntity Update After Create, ex: {0}",ex),( Crm2CrmTrace.Sw.TraceError ) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                                }
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Update After Create: {0}",retupd),Crm2CrmTrace.Sw.Info);
                            }
                        }
                        break;
                        case CrmStr.customerrelationship:
                        if ( Lookup2Set.Count > 0 )
                        {
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Update After Create with converserrelationshipid: {0}",newPrimaryKeyValue),Crm2CrmTrace.Sw.Info);
                            DynEntity converser =   Lookup2Set[CrmStr.converserelationshipid];
                            converser.AddLookupProperty(CrmStr.converserelationshipid,CrmStr.customerrelationship,newPrimaryKeyValue);
                            converser.adminUpdate();
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity Update Ok After Create with converserrelationshipid: {0}",newPrimaryKeyValue),Crm2CrmTrace.Sw.Info);
                        }
                        break;
                    }
                }

                // Add it to dic to preserve create/update status
                if ( newAcc != null )
                {
                    Guid strKey             =   s.PrimaryKeyGuidValue;
                    if ( !dic.ContainsKey(strKey) )
                        dic.Add(strKey,newAcc);
                }

                if ( stateCode != string.Empty )
                {
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity after Create setting stateCode: '{0}'",stateCode),Crm2CrmTrace.Sw.Info);
                    // avoid warning message generated for open lead when already in open mode 
                    int intState        =   Wrapper2.Util.StateCodeValueFromName(SchemaName,stateCode);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity int stateCode: '{0}'",intState),Crm2CrmTrace.Sw.Info);

                    switch ( SchemaName )
                    {
                        case CrmStr.lead:
                        if ( intState == CrmStr.StateOpen )
                            break;
                        // when lead are created as a regarding option for an activity, they can be closed before the activity is created
                        // we push them in a list of status to set after create or update
                        if ( intState == CrmStr.StateDisqualified && _EntranceLevel > 1 )
                        {
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity pushing status for: {0}, newPrimaryKeyValue: {1}, stateCode: {2}, statusCode: {3}.",
                                    new object[] { SchemaName,newPrimaryKeyValue,stateCode,statusCode }),Crm2CrmTrace.Sw.Info);
                            Statu2SetList.Add(new State2Set() { dynEn = newAcc,PrimaryKeyValue = newPrimaryKeyValue,State = intState,Status = statusCode });
                            break;
                        }
                        Wrapper.Util.SetStateOperation(SchemaName,newPrimaryKeyValue,intState,statusCode);
                        break;
                        case CrmStr.opportunity:
                        // We need to copy an opportunityclose to close it
                        if ( intState != CrmStr.StateOpen )
                            NeedOpportunityClose = true;
                        break;
                        case CrmStr.salesorder:
                        // We need to copy an orderclose to close it
                        if ( intState != CrmStr.StateActive )
                            NeedOrderClose = true;
                        break;
                        case CrmStr.quote:
                        // We need to copy an opportunityclose to close it
                        if ( intState != CrmStr.StateQuoteActive )
                            NeedQuoteClose = true;
                        break;

                        default:
                        // on base level we set all status pushed when creating lookup values
                        if ( _EntranceLevel == 1 )
                        {
                            foreach ( State2Set st in Statu2SetList )
                            {
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity applying status for pushed: {0}, newPrimaryKeyValue: {1}, stateCode: {2}, statusCode: {3}.",
                                        new object[] { st.dynEn.SchemaName,st.PrimaryKeyValue,st.State,st.Status }),Crm2CrmTrace.Sw.Info);
                                Wrapper.Util.SetStateOperation(st.dynEn.SchemaName,st.PrimaryKeyValue,st.State,st.Status);
                            }
                            Statu2SetList.Clear();
                        }
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity setting stateCode: {0}, Status : {1}",intState,statusCode),Crm2CrmTrace.Sw.Info);
                        Wrapper.Util.SetStateOperation(SchemaName,newPrimaryKeyValue,intState,statusCode);
                        break;
                    }
                }
            }
            catch ( FatalException )
            {
                throw;
            }
            catch ( InnerException )
            {
                if ( StopOnFirstError || MaxErrors <= TotErrorCount + ( errCount ) )
                {
                    _EntranceLevel--;
                    throw;
                }
            }
            catch ( CRMWrapperException sx )
            {
                string msg          =   string.Format("[E]Crm2Crm CopyDynEntity wrapper ex: {0}",sx);
                DicErrors.Add(string.Format("Copy entity name {0} failed for {1}",SchemaName,( !s.HasPrimaryField ) ? s.PrimaryKeyGuidValue.ToString() : s.PrimaryFieldStringValue));
                if ( Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine(msg,( Crm2CrmTrace.Sw.TraceError ) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);

                if ( ( sx.InnerException != null ) && ( sx.InnerException is System.Net.WebException ) )
                {
                    System.Net.WebException ex2 =   (System.Net.WebException)sx.InnerException;
                    if ( ( ex2.InnerException != null ) && ( ex2.InnerException is System.Net.Sockets.SocketException ) )
                    {
                        msg = "[E]Crm2Crm CopyDynEntity Fatal sockets Exception";
                        if ( Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine(msg,( Crm2CrmTrace.Sw.TraceError ) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                        throw new FatalException(msg,sx);
                    }
                }

                if ( StopOnFirstError || MaxErrors <= TotErrorCount + ( TotErrorCount + ( errCount++ ) ) )
                {
                    _EntranceLevel--;
                    throw new InnerException(msg,sx);
                }
            }
            catch ( Exception ex )
            {
                string msg          =   string.Format("[E]Crm2Crm CopyDynEntity  ex: {0}",ex);
                DicErrors.Add(string.Format("Copy entity name {0} failed for {1}",SchemaName,( string.IsNullOrEmpty(s.PrimaryFieldName) ) ? s.PrimaryKeyGuidValue.ToString() : s.PrimaryFieldStringValue));
                if ( Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine(msg,( Crm2CrmTrace.Sw.TraceVerbose ) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                if ( StopOnFirstError || MaxErrors <= TotErrorCount + ( TotErrorCount + ( errCount++ ) ) )
                {
                    _EntranceLevel--;
                    throw new InnerException(msg,ex);
                }
            }
            if (Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyDynEntity END entity: {0} isOk: {1}, re-entranceLevel: {2}",
                    SchemaName,isOk,_EntranceLevel),Crm2CrmTrace.Sw.Info);
            _EntranceLevel--;
            if ( isOk )
                return newAcc;
            return null;
        }
        
        /// <summary>
        /// Read all the entities from source with entityname
        /// Duplicate all of them
        /// </summary>
        public void CopyAll()
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll BEG entityName: {0}, FullCopy: {1}.",entityName,FullCopy),Crm2CrmTrace.Sw.Info);
            int count                                               =   0;
            errCount                                                =   0;
            CreateCount                                             =   0;
            DupCount                                                =   0;
            UpdateCount                                             =   0;
            ProgressPrimCount++;
            try
            {
                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper2,ResetWrapper,entityName);
                InternalQueryExpression qe                          =   null;
                // We don't need addresses already created with accounts or contacts
                if (entityName == CrmStr.customeraddress)
                {
                    qe                                              =   new InternalQueryExpression();
                    qe.EntityName                                   =   CrmStr.customeraddress;
                    InternalAllColumns RequestCols                  =   new InternalAllColumns();
                    InternalFilterExpression fi                     =   new InternalFilterExpression();
                    InternalConditionExpression ex                  =   new InternalConditionExpression();
                    ex.AttributeName                                =   CrmStr.addressnumber;
                    ex.Operator                                     =   InternalConditionOperator.GreaterThan;
                    ex.Values                                       =   new string[]{"2"};
                    if ( !FullCopy )
                    {
                        DateTime startdate                          =   (RadStartDate.SelectedDate.HasValue ) ? RadStartDate.SelectedDate.Value:CRMUtil.minDateTime;
                        string reqDate                              =   string.Format(CultureInfo.InvariantCulture, "{0:s}",startdate);
                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll startdate: {0}, reqDate: {1}.",startdate,reqDate),Crm2CrmTrace.Sw.Info);
                        InternalConditionExpression ex1             =   new InternalConditionExpression();
                        ex1.AttributeName                           =   CrmStr.createdon;
                        ex1.Operator                                =   InternalConditionOperator.OnOrAfter;
                        ex1.Values                                  =   new string[]{reqDate};
                        fi.Conditions                               =   new InternalConditionExpression[]{ex,ex1};
                    }
                    else fi.Conditions                              =   new InternalConditionExpression[]{ex};
                    qe.ColumnSet                                    =   RequestCols;
                    qe.Criteria                                     =   fi;
                }
                else if ( ! FullCopy )
                {
                    DateTime startdate                              =   (RadStartDate.SelectedDate.HasValue ) ? RadStartDate.SelectedDate.Value:CRMUtil.minDateTime;
                    string reqDate                                  =   string.Format(CultureInfo.InvariantCulture, "{0:s}",startdate);
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll startdate: {0}, reqDate: {1}.",startdate,reqDate),Crm2CrmTrace.Sw.Info);
                    qe                                              =   new InternalQueryExpression();
                    qe.EntityName                                   =   entityName;
                    InternalAllColumns RequestCols                  =   new InternalAllColumns();
                    InternalFilterExpression fi                     =   new InternalFilterExpression();
                    InternalConditionExpression ex                  =   new InternalConditionExpression();
                    ex.AttributeName                                =   CrmStr.createdon;
                    ex.Operator                                     =   InternalConditionOperator.OnOrAfter;
                    ex.Values                                       =   new string[]{reqDate};
                    fi.Conditions                                   =   new InternalConditionExpression[]{ex};
                    qe.ColumnSet                                    =   RequestCols;
                    qe.Criteria                                     =   fi;
                }
                // Retrieve all
                InternalBusinessEntityCollection allEnt             =   allEntQuery.adminRetrieve(qe);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                _TConfig                                            =   null;
                _TConfig2                                           =   null;
                dynEntList.Clear();
                // Transform them in DynEntities and insert them in dynEntList
                Wrapper2.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                        DynEntity ob                                =   DynEntity.CreateFromDynamicEntity(Wrapper2,de,_columnDescriptors);
                        ob.EntityMData                              =   TConfig2.entityMetaData;
                        _columnDescriptors                          =   ob.PropertyDescriptorCollection;
                        dynEntList.Add(ob);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll inserting in dynEntList, after Ctor schemaName: [{0}], type: {1}", ob.SchemaName, ob),Crm2CrmTrace.Sw.Info);
                        return true;
                    }
                    );
                // duplicate entities, recurring to links like lookup or customers, etc.
                count                                               =   dynEntList.Count;
                ResetProgressSecTotal(count);
                SetUpdateProgress(string.Format("Copy {0}s starts",entityName),ProgressPrimCount,ProgressSecCount);
                if (Crm2CrmTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll before copying entityName: {0} found Count: {1}.",entityName,count),Crm2CrmTrace.Sw.Info);
                for (int i = 0; i < count; i++)
                {
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll Copy process entity: {0}, i: {1}/{2}",entityName, i+1,count), Crm2CrmTrace.Sw.Info);
                    DynEntity s                                     =   dynEntList[i];
                    string PrimaryFieldStringValue                  =   s.PrimaryFieldStringValue;
                    SetUpdateProgress(string.Format("{0} '{1}'",entityName,PrimaryFieldStringValue),ProgressPrimCount,ProgressSecCount++);
                    // filter for already created records
                    if ( DicDic.ContainsKey(entityName) && DicDic[entityName].ContainsKey(s.PrimaryKeyGuidValue) )
                    {
                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll already created {0}, found: {1} jumping over copy.",entityName,s.PrimaryKeyGuidValue),Crm2CrmTrace.Sw.Info);
                        continue;
                    }
                    // For lot of 'child' entities, parent must be there when doing a full copy
                    bool missingParent                              =   false;
                    Guid pID                                        =   Guid.Empty;
                    if ( FullCopy && ( entityName == CrmStr.quotedetail ))
                    {
                        pID                                         =   ((ADNDynQuoteDetail)s).quoteid;
                        if ( !DicDic.ContainsKey(CrmStr.quote) || !DicDic[CrmStr.quote].ContainsKey(pID) )
                            missingParent                               =   true;
                    }
                    if ( FullCopy && (entityName == CrmStr.orderdetail ) )
                    {
                        pID                                         =   ((ADNDynSalesOrderDetail)s).salesorderid;
                        if ( !DicDic.ContainsKey(CrmStr.salesorder) || !DicDic[CrmStr.salesorder].ContainsKey(pID) )
                            missingParent                               =   true;
                    }
                    if ( FullCopy && (entityName == CrmStr.invoicedetail ) )
                    {
                        pID                                         =   ((ADNDynInvoiceDetail)s).invoiceid;
                        if ( !DicDic.ContainsKey(CrmStr.invoice) || !DicDic[CrmStr.invoice].ContainsKey(pID) )
                            missingParent                           =   true;
                    }
                    if ( FullCopy && (entityName == CrmStr.productpricelevel ))
                    {
                        pID                                         =   ((ADNDynProductPricelevel)s).productid;
                        if ( !DicDic.ContainsKey(CrmStr.product) || !DicDic[CrmStr.product].ContainsKey(pID) )
                            missingParent                           =   true;
                        pID         =   ((ADNDynProductPricelevel)s).pricelevelid;
                        if ( !missingParent && !DicDic.ContainsKey(CrmStr.pricelevel) || !DicDic[CrmStr.pricelevel].ContainsKey(pID) )
                            missingParent                           =   true;
                    }
                    if ( missingParent )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll missing parent entity:{0}, ID: {1}.",entityName,pID),Crm2CrmTrace.Sw.Info);
                        continue;
                    }

                    DynEntity newAcc                                =   CopyDynEntity(s,TConfig,null);
                    if ( entityName == CrmStr.product )
                    {
                        if ( ((ADNDynProduct)s).iskit )
                            CopyKitMembers((ADNDynProduct)s,(ADNDynProduct)newAcc,TConfig);
                        CopySubstitutes((ADNDynProduct)s,(ADNDynProduct)newAcc,TConfig);
                    }
                    // Marketing list need to be filled
                    if ( entityName == CrmStr.list )
                    {
                        CopyListMembers((ADNDynList)s,(ADNDynList)newAcc);
                    }

                    if ( entityName == CrmStr.salesliterature )
                    {
                        CopyRelatedProducts((ADNDynSalesLiterature)s,(ADNDynSalesLiterature)newAcc,TConfig);
                    }
                }
                if ( errCount > 0 )
                    DicErrors.Add(string.Format("{0} errors count: {1}",entityName,errCount));
                DicOk.Add(entityName,new ResultCount(){ Copied=CreateCount, Created=CreateCount,Duplicates=DupCount,Updated=UpdateCount,Errors=errCount});

                TotErrorCount                                       +=  errCount;
                TotCreateCount                                      +=  CreateCount;
                TotDupCount                                         +=  DupCount;
                TotUpdCount                                         +=  UpdateCount;
            }
            catch ( FatalException )
            {
                throw;
            }
            catch(InnerException)
            {
                _EntranceLevel          =   0;
                TotErrorCount           +=  errCount;
                if ( StopOnFirstError || MaxErrors <= TotErrorCount )
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                _EntranceLevel          =   0;
                string msg              =   string.Format("[E]Crm2Crm CopyAll ex : {0}", ex);
                DicErrors.Add(string.Format("Copy failed for entity name {0}",entityName));
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                TotErrorCount           +=  (++errCount);
                if ( StopOnFirstError || MaxErrors <= TotErrorCount )
                    throw new InnerException(msg,ex);
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAll END entity: {0}, Count: {1}",entityName,count),Crm2CrmTrace.Sw.Info);
        }
        
        /// <summary>
        /// val3 contains the name from the lookup used for display in forms
        /// val2 is null and should contain the entityname
        /// Val is the Guid for the lookup
        /// parentPrimaryFieldStringValue contains the value in primaryField for calling entity
        /// Returns true if lookup has been created
        /// </summary>
        DynEntity RetrieveLookup(DynEntity newAcc,string Name,Guid Val,object val3,string parentPrimaryFieldStringValue,object val2)
        {
            string lookupSchema                 =   (val2 == null ) ? string.Empty:(string)val2; // For CRM3  val2 is null
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup BEG Entity: {0}, Lookup Name: '{1}', lookupSchema: '{2}'",
                    newAcc.SchemaName,Name,lookupSchema),Crm2CrmTrace.Sw.Info);
            // type is infortunately always empty for lookup we must ask for metadatadefinition to get the associated entity
            List<string> entLst                 =   null;

            // Far faster
            if ( !string.IsNullOrEmpty(lookupSchema) )
            {
                DynEntity newDyn            =   null;
                if ( DicDic.ContainsKey(lookupSchema) && DicDic[lookupSchema].ContainsKey(Val) )
                {
                    newDyn              =   DicDic[lookupSchema][Val];
                    newAcc.AddLookupProperty(Name, lookupSchema, newDyn.PrimaryKeyGuidValue);
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup END found in Dic Entity: {0}, Lookup Name: '{1}', lookupSchema: '{2}'",
                            newAcc.SchemaName,Name,lookupSchema),Crm2CrmTrace.Sw.Info);
                    return newDyn; // not created
                }
                entLst                          =   new List<string>(1);
                entLst.Add(lookupSchema);
            }
            else if ( newAcc.SchemaName != entityName )
                 entLst                         =   NewTConfig2(newAcc.SchemaName).FindPotentialLookupEntities(Name);
            else entLst                         =   TConfig2.FindPotentialLookupEntities(Name);
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup BEG entLst.Count: {0}",entLst.Count),Crm2CrmTrace.Sw.Info);
            //first loop for accounts/contacts/systemuser
            foreach(string otp in entLst)
            {
                if ( Crm2CrmTrace.Sw.TraceVerbose )
                   Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup trying entity: '{0}'",otp),Crm2CrmTrace.Sw.Info);

                if ( !string.IsNullOrEmpty(lookupSchema) && ( lookupSchema != otp )  )
                    continue;
            
                string strVal2                  =   string.Empty;
                bool created                    =   false;

                switch(otp)
                {
                    case CrmStr.account:
                        ADNDynAccount waccount   =   null;
                        ADNDynAccount waccount2  =   new ADNDynAccount(Wrapper2,(string)val3);
                        waccount2.EntityID      =   Val;
                        if ( !waccount2.adminRetrieve() )
                            break;
                        strVal2                 =   waccount2.name;
                        waccount                =   Wrapper.Util.FindAccountByName(strVal2,true,ref created);
                        if ( waccount != null )
                        {
                            if (Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup {0} account: {1}-{2}",
                                    (created) ? "created":"found",waccount.name,waccount.accountid),Crm2CrmTrace.Sw.Info);
                            newAcc.AddLookupProperty(Name,otp,waccount.accountid);
                            // we push it to avoid any duplication
                            if ( created && !DicDic[CrmStr.account].ContainsKey(Val) ) // could have been added if created
                                DicDic[CrmStr.account].Add(Val,waccount);
                            return waccount;
                        }
                        break;
                    case CrmStr.contact:
                        ADNDynContact wcontact      =   null;
                        ADNDynContact wcontact2 =   new ADNDynContact(Wrapper2,string.Empty,string.Empty);
                        wcontact2.EntityID      =   Val;
                        if ( !wcontact2.adminRetrieve() )
                            break;
                        wcontact                =   Wrapper.Util.FindContactByName(wcontact2.firstname,wcontact2.lastname,true,ref created);
                        if ( wcontact != null )
                        {
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup {0} contact: {1}-{2}",
                                    (created) ? "created":"found",wcontact.lastname,wcontact.contactid),Crm2CrmTrace.Sw.Info);
                            newAcc.AddLookupProperty(Name,otp,wcontact.contactid);
                            // we push it to avoid any duplication
                            if ( created && !DicDic[CrmStr.contact].ContainsKey(Val) ) // could have been added if created
                                DicDic[CrmStr.contact].Add(Val,wcontact);
                            return wcontact;
                        }
                        break;
                    case CrmStr.lead:
                        ADNDynLead wlead            =   null;
                        ADNDynLead  wlead2       =   new ADNDynLead(Wrapper2,string.Empty,string.Empty);
                        wlead2.EntityID         =   Val;
                        if ( !wlead2.adminRetrieve() )
                            break;
                        wlead                   =   Wrapper.Util.FindLeadByName(wlead2,true,ref created,
                            delegate(DynEntity s)
                            {
                                EntityConfig Tconf  =   null;
                                if ( entityName == CrmStr.lead )
                                    Tconf           =   TConfig;
                                else Tconf          =   new EntityConfig(Wrapper,CrmStr.lead );
                                return CopyDynEntity(s,Tconf,parentPrimaryFieldStringValue); 
                            }
                            );
                        if ( wlead != null )
                        {
                            if (Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup {0} lead: {1}-{2}",
                                    (created) ? "created":"found",wlead.lastname,wlead.leadid),Crm2CrmTrace.Sw.Info);
                            newAcc.AddLookupProperty(Name,otp,wlead.leadid);
                            // we push it to avoid any duplication
                            if ( created && !DicDic[CrmStr.lead].ContainsKey(Val) ) // could have been added if created
                                DicDic[CrmStr.lead].Add(Val,wlead);
                            return wlead;
                        }
                        break;
                    case CrmStr.systemuser:
                        ADNDynSystemUser sysuser        =   null;
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup trying systemuser sysuserDic.Cont: {0}",DicDic[CrmStr.systemuser].Count),Crm2CrmTrace.Sw.Info);
                        ADNDynSystemUser sysuser2   =   new ADNDynSystemUser(Wrapper2, (string)val3);
                        sysuser2.EntityID           =   Val;
                        if ( !sysuser2.adminRetrieve() )
                            break;
                        if (FindSystemUserByDomainName)
                            sysuser = Wrapper.Util.FindSystemUserByDomainName(sysuser2.domainname);
                        else
                        {
                            created                 =   false;
                            sysuser                 =   Wrapper.Util.FindSystemUserByFirstLastName(sysuser2.firstname, sysuser2.lastname, false, ref created);
                        }
                        if ( sysuser != null )
                        {
                            if (Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup found systemuser: {0}, Val: {1}",sysuser.fullname,Val),Crm2CrmTrace.Sw.Info);
                            newAcc.AddLookupProperty(Name,otp,sysuser.systemuserid);
                            if (!DicDic[CrmStr.systemuser].ContainsKey(Val))
                                DicDic[CrmStr.systemuser].Add(Val,sysuser);
                            return sysuser;
                        }
                        break;
                }
            }

            // not in account/contact/lead/systemuser we search for others entities
            foreach(string otp in entLst)
            {
                if ( Crm2CrmTrace.Sw.TraceVerbose )
                   Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup trying entity : '{0}'",otp),Crm2CrmTrace.Sw.Info);
            
                string strVal2                      =   string.Empty;
                bool created                        =   false;

                if ( !string.IsNullOrEmpty(lookupSchema) && ( lookupSchema != otp )  )
                    continue;
                switch(otp)
                {
                    case CrmStr.lead:
                    case CrmStr.account:
                    case CrmStr.contact:
                    case CrmStr.systemuser:
                        break;
                    default:
                        DynEntity newDyn            =   null;
                        DynEntity wdyn2             =   DynEntity.Create2RetrieveDynamicEntity(Wrapper2, otp, Val);
                        if (!wdyn2.adminRetrieve()) // this is not the good entity schemaname loop to next
                            break;
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup Lookup found in source entity: '{0}' for lookup: {1}.",otp,Name),Crm2CrmTrace.Sw.Info);
                        newDyn                  =   Wrapper.Util.FindOrReplicateEntity(wdyn2, wdyn2.CanCreate, ref created,
                                                            delegate(DynEntity s)
                                                            {
                                                                EntityConfig Tconf  =   null;
                                                                if ( s.SchemaName == entityName )
                                                                    Tconf           =    TConfig;
                                                                else Tconf          =   new EntityConfig(Wrapper,s.SchemaName);
                                                                // we pass the parentlookup string name as parameter -> used for uomschedule
                                                                return CopyDynEntity(s,Tconf,parentPrimaryFieldStringValue); // beware stack overflow ?
                                                            }
                                                            );
                        if (newDyn != null)
                        {
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveLookup {0} entity: {1}-{2}",
                                    (created) ? "created" : "found", newDyn.PrimaryFieldStringValue, newDyn.PrimaryKeyGuidValue), Crm2CrmTrace.Sw.Info);
                            newAcc.AddLookupProperty(Name, otp, newDyn.PrimaryKeyGuidValue);
                            return newDyn;
                        }
                        break;
                }
            }
            return null;
        }

        void RetrieveCustomer(DynEntity newAcc,string Name,Guid Val,object val2,object val3)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer Entity: {0}, Customer Name: {1}",newAcc.SchemaName,Name),Crm2CrmTrace.Sw.Info);
            // type is infortunately always empty for lookup we must ask for metadatadefinition to get the associated entity
            string otp                          =   (string)val2;
            if ( Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer Entity : '{0}'",otp),Crm2CrmTrace.Sw.Info);
            
            string strVal2                      =   string.Empty;
            bool created                        =   false;

            switch(otp)
            {
                case CrmStr.account:
                    ADNDynAccount waccount      =   null;
                    if (DicDic[CrmStr.account].ContainsKey(Val))
                    {
                        waccount                =   (ADNDynAccount )DicDic[CrmStr.account][Val];
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer found in dic account name: {0}",waccount.name),Crm2CrmTrace.Sw.Info);
                    }
                    else
                    {
                        ADNDynAccount waccount2 =   new ADNDynAccount(Wrapper2,(string)val3);
                        waccount2.EntityID      =   Val;
                        waccount2.adminRetrieve();
                        strVal2                 =   waccount2.name;
                        waccount                =   Wrapper.Util.FindAccountByName(strVal2,true,ref created);
                    }
                    if ( waccount != null )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer {0} account: {1}-{2}",
                                (created) ? "created":"found",waccount.name,waccount.accountid),Crm2CrmTrace.Sw.Info);
                        newAcc.AddCustomerProperty(Name,otp,waccount.accountid);
                        if ( created && !DicDic[CrmStr.account].ContainsKey(Val) ) // could have been added if created
                            DicDic[CrmStr.account].Add(Val,waccount);
                    }
                    break;
                case CrmStr.contact:
                    ADNDynContact wcontact      =   null;
                    if (DicDic[CrmStr.contact].ContainsKey(Val))
                    {
                        wcontact                =   (ADNDynContact)DicDic[CrmStr.contact][Val];
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer found in dic contact lastname: {0}",wcontact.lastname),Crm2CrmTrace.Sw.Info);
                    }
                    else
                    {
                        ADNDynContact wcontact2 =   new ADNDynContact(Wrapper2,string.Empty,string.Empty);
                        wcontact2.EntityID      =   Val;
                        wcontact2.adminRetrieve();
                        wcontact                =   Wrapper.Util.FindContactByName(wcontact2.firstname,wcontact2.lastname,true,ref created);
                    }
                    if ( wcontact != null )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer {0} contact: {1}-{2}",
                                (created) ? "created":"found",wcontact.lastname,wcontact.contactid),Crm2CrmTrace.Sw.Info);
                        newAcc.AddCustomerProperty(Name,otp,wcontact.contactid);
                        if ( created && !DicDic[CrmStr.contact].ContainsKey(Val) ) // could have been added if created
                            DicDic[CrmStr.contact].Add(Val,wcontact);
                    }
                    break;

                case CrmStr.lead:
                    ADNDynLead wlead            =   null;
                    if ( DicDic[CrmStr.lead].ContainsKey(Val))
                    {
                        wlead                   =   (ADNDynLead)DicDic[CrmStr.lead][Val];
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer found in dic lead lastname: {0}",wlead.lastname),Crm2CrmTrace.Sw.Info);
                    }
                    else
                    {
                        ADNDynLead wlead2       =   new ADNDynLead(Wrapper2,string.Empty,string.Empty);
                        wlead2.EntityID         =   Val;
                        wlead2.adminRetrieve();
                        wlead                   =   Wrapper.Util.FindLeadByName(wlead2,true,ref created,
                                delegate(DynEntity s)
                                {
                                    EntityConfig Tconf  =   null;
                                    if ( entityName == CrmStr.lead )
                                        Tconf           =    TConfig;
                                    else Tconf          =   new EntityConfig(Wrapper,CrmStr.lead );
                                    return CopyDynEntity(s,Tconf,null); 
                                }
                                );
                    }
                    if ( wlead != null )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer {0} lead: {1}-{2}",
                                (created) ? "created":"found",wlead.lastname,wlead.leadid),Crm2CrmTrace.Sw.Info);
                        newAcc.AddCustomerProperty(Name,otp,wlead.leadid);
                        if ( created && !DicDic[CrmStr.lead].ContainsKey(Val) ) // could have been added if created
                            DicDic[CrmStr.lead].Add(Val,wlead);
                    }
                    break;

                default:
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer entity: '{0}', trying name: {1}",otp,Name),Crm2CrmTrace.Sw.Info);
                    DynEntity wdyn2         =   new DynEntity(Wrapper2,otp,Val);
                    wdyn2.adminRetrieve();
                    strVal2                 =   wdyn2.PrimaryFieldStringValue;
                    DynEntity newDyn        =   Wrapper.Util.FindOrReplicateEntity(wdyn2, wdyn2.CanCreate, ref created,
                        delegate(DynEntity s)
                        {
                            EntityConfig Tconf  =   null;
                            if ( s.SchemaName == entityName )
                                Tconf           =    TConfig;
                            else Tconf          =   new EntityConfig(Wrapper,s.SchemaName);
                            return CopyDynEntity(s,Tconf,null);
                        }
                        );
                    if (newDyn != null)
                    {
                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RetrieveCustomer {0} entity: {1}-{2}",
                                (created) ? "created" : "found", newDyn.PrimaryFieldStringValue, newDyn.EntityID), Crm2CrmTrace.Sw.Info);
                        newAcc.AddCustomerProperty(Name, otp, newDyn.PrimaryKeyGuidValue);
                    }
                    break;
            }
        }

        void FindOwner(string otp,string Name,DynEntity newAcc,Guid Val,string val3)
        {
            switch(otp)
            {
                case CrmStr.systemuser:
                    ADNDynSystemUser sysuser        =   null;
                    if (DicDic[CrmStr.systemuser].ContainsKey(Val))
                    {
                        sysuser                     =   (ADNDynSystemUser)DicDic[CrmStr.systemuser][Val];
                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FindOwner found in dic systemuser: {0}, Val: {1}", sysuser.fullname,Val), Crm2CrmTrace.Sw.Info);
                    }
                    else
                    {
                        ADNDynSystemUser sysuser2   =   new ADNDynSystemUser(Wrapper2,val3);
                        sysuser2.EntityID           =   Val;
                        sysuser2.adminRetrieve();
                        if (FindSystemUserByDomainName)
                            sysuser = Wrapper.Util.FindSystemUserByDomainName(sysuser2.domainname);
                        else
                        {
                            bool created            =   false;
                            sysuser = Wrapper.Util.FindSystemUserByFirstLastName(sysuser2.firstname, sysuser2.lastname, false, ref created);
                        }
                    }
                    if ( sysuser != null )
                    {
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FindOwner found systemuser: {0}",sysuser.fullname),Crm2CrmTrace.Sw.Info);
                        newAcc.AddOwnerProperty(Name,otp,sysuser.systemuserid);
                        if (!DicDic[CrmStr.systemuser].ContainsKey(Val))
                            DicDic[CrmStr.systemuser].Add(Val,sysuser);
                    }
                    break;
                default:
                    break;
                }
        }

        /// <summary>
        /// Insert in global dictionnaries the correspondance between the inner business units, so any call to BU will retrieve the base BU
        /// As an enhancementwe could map the BUs
        /// </summary>
        public void InitBusinessUnits()
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm InitBusinessUnits BEG.", Crm2CrmTrace.Sw.Info);
            try
            {
                Guid SourceBUId     =   Wrapper2.InnerBusinessUnit.businessunitid;
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm InitBusinessUnits SourceBUId: {0}.",SourceBUId), Crm2CrmTrace.Sw.Info);
                DicDynEnt dic       =   new DicDynEnt();
                DicDic.Add(CrmStr.businessunit,dic);
                dic.Add(SourceBUId,Wrapper.InnerBusinessUnit);
            }
            catch (Exception ex)
            {
                if (Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm InitBusinessUnits ex: {0}", ex), Crm2CrmTrace.Sw.Info);
                throw;
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm InitBusinessUnits END.", Crm2CrmTrace.Sw.Info);
        }


        public void CopyAllAccounts()
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts BEG FullCopy: {0}.",FullCopy),Crm2CrmTrace.Sw.Info);
            int count                                               =   0;
            errCount                                                =   0;
            CreateCount                                             =   0;
            DupCount                                                =   0;
            UpdateCount                                             =   0;

            List<ADNDynAccount> dynAccounts2                        =   new List<ADNDynAccount>();
            ProgressPrimCount++;
            try
            {
                GenericDynQueryMultiple<ADNDynAccount> allAccountQuery   =   new GenericDynQueryMultiple<ADNDynAccount>(Wrapper2,ResetWrapper,CrmStr.account);
                InternalQueryExpression qe                          =   null;
                if ( !FullCopy )
                {
                    DateTime startdate                              =   (RadStartDate.SelectedDate.HasValue ) ? RadStartDate.SelectedDate.Value:CRMUtil.minDateTime;
                    
                    string reqDate                                  =   string.Format(CultureInfo.InvariantCulture, "{0:s}",startdate);
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts startdate: {0}, reqDate: {1}.",startdate,reqDate),Crm2CrmTrace.Sw.Info);
                    qe                                              =   new InternalQueryExpression();
                    qe.EntityName                                   =   entityName;
                    InternalAllColumns RequestCols                  =   new InternalAllColumns();
                    InternalFilterExpression fi                     =   new InternalFilterExpression();
                    InternalConditionExpression ex                  =   new InternalConditionExpression();
                    ex.AttributeName                                =   CrmStr.createdon;
                    ex.Operator                                     =   InternalConditionOperator.OnOrAfter;
                    ex.Values                                       =   new string[]{reqDate};
                    fi.Conditions                                   =   new InternalConditionExpression[]{ex};
                    qe.ColumnSet                                    =   RequestCols;
                    qe.Criteria                                     =   fi;
                }
                InternalBusinessEntityCollection allAccount         =   allAccountQuery.adminRetrieve(qe);
                _TConfig                                            =   null;
                _TConfig2                                           =   null;
                PropertyDescriptorCollection _columnDescriptors     =   null;
                Wrapper2.Util.ExecForEachDynamicEntity(allAccount,
                    delegate(InternalDynamicEntity de)
                    {
                        ADNDynAccount ob                            =    new ADNDynAccount(Wrapper2, de, _columnDescriptors,null);
                        ob.EntityMData                              =   TConfig2.entityMetaData;
                        _columnDescriptors                          =   ob.PropertyDescriptorCollection;
                        dynAccounts2.Add(ob);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts after Ctor for DynEntity: {0}.", ob.SchemaName),Crm2CrmTrace.Sw.Info);
                        return true;
                    }
                    );
                count                                               =   dynAccounts2.Count;
                ResetProgressSecTotal(count);
                SetUpdateProgress("Copy accounts starts",ProgressPrimCount,ProgressSecCount);
                for (int i = 0; i < count; i++)
                {
                    DynEntity s                                     =   dynAccounts2[i];
                    DynEntity dup                                   =   null;
                    try
                    {
                        string PrimaryFieldStringValue              =   s.PrimaryFieldStringValue;
                        SetUpdateProgress(string.Format("Account '{0}'",PrimaryFieldStringValue),ProgressPrimCount,ProgressSecCount++);
                        ADNDynAccount newAcc                        =   null;
                        if (ShoudCheckDuplicates(CrmStr.account))
                        {
                            if ( ExistDuplicates(s,PrimaryFieldStringValue,ref dup) && (dup.modifiedonLocalDate >= s.modifiedonLocalDate )) // we keep duplicates with modified value equal or more recent than org
                                continue;
                        }
                        newAcc                                      =   new ADNDynAccount(Wrapper,PrimaryFieldStringValue);
                        string stateCode                            =   string.Empty;
                        int statusCode                              =   0;
                        // Needed to respect real levels inside CopyDynEntity
                        _EntranceLevel++;
                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts i: {0}, PrimaryFieldStringValue: {1}",  i,PrimaryFieldStringValue ),Crm2CrmTrace.Sw.Info);
                        Wrapper2.Util.ExecForEachDynamicEntityProperty(s,
                            delegate(string Name,object Val,object val2,object val3,AttributeInternalType tp)
                            {
                                if (!TConfig.attributesDic.ContainsKey(Name))
                                {
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts Property not in V4 Name: {0}",Name),Crm2CrmTrace.Sw.Info);
                                }
                                InternalAttributeMetadata attributeMetaData =   TConfig[Name];
                                bool ValidForCreate             =   Wrapper.Util.ExtractAttributeFieldAsBool(attributeMetaData,InternalAttributeFields.ValidForCreate);
                                bool ValidForUpdate             =   Wrapper.Util.ExtractAttributeFieldAsBool(attributeMetaData,InternalAttributeFields.ValidForUpdate);
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccount Name: {0}, ValidForCreate: {1}, ValidForUpdate: {2}.",Name,ValidForCreate,ValidForUpdate),Crm2CrmTrace.Sw.Info);
                                if (!ValidForCreate && !ValidForUpdate)
                                {
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts Not Valid For Create/Update Name: {0}",Name),Crm2CrmTrace.Sw.Info);
                                    if ( Name.Equals(CrmStr.statecode))
                                    {
                                        stateCode               = (string)Val;
                                        if (Crm2CrmTrace.Sw.TraceVerbose)
                                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccount stateCode for {0}: {1}", entityName, Val), Crm2CrmTrace.Sw.Info);
                                    }
                                    return true;
                                }
                                switch(tp)
                                {
                                    case AttributeInternalType.Float:
                                        if ( Val is double )
                                                newAcc.AddFloatProperty(Name,(double)Val);
                                        else    newAcc.AddFloatProperty(Name,(float)Val);
                                        break;
                                    case AttributeInternalType.Integer:
                                        newAcc.AddNumberProperty(Name,(int)Val);
                                        break;
                                    case AttributeInternalType.Status:
                                        if (Name.Equals(CrmStr.statuscode))
                                        {
                                            statusCode = (int)Val;
                                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccount statuscode for {0}: {1}", entityName, Val), Crm2CrmTrace.Sw.Info);
                                        }
                                        else
                                            newAcc.AddStatusProperty(Name, (int)Val);
                                        break;
                                    case AttributeInternalType.Picklist:
                                        newAcc.AddPicklistProperty(Name,(int)Val);
                                        break;
                                    case AttributeInternalType.Decimal:
                                        newAcc.AddDecimalProperty(Name,(decimal)Val);
                                        break;
                                    case AttributeInternalType.State:
                                        if (Name.Equals(CrmStr.statecode))
                                        {
                                            stateCode = (string)Val;
                                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccount stateCode for {0}: {1}", entityName, Val), Crm2CrmTrace.Sw.Info);
                                        }
                                        break;
                                    case AttributeInternalType.String:
                                        newAcc.AddStringProperty(Name,(string)Val);
                                        break;
                                    case AttributeInternalType.Memo:
                                        newAcc.AddStringProperty(Name,(string)Val);
                                        break;
                                    case AttributeInternalType.DateTime:
                                        newAcc.AddDateTimeProperty(Name,(string)Val);
                                        break;
                                    case AttributeInternalType.Money:
                                        newAcc.AddMoneyProperty(Name,(decimal)Val);
                                        break;
                                    case AttributeInternalType.Boolean:
                                        newAcc.AddBooleanProperty(Name,(bool)Val);
                                        break;
                                    case AttributeInternalType.PrimaryKey:
                                        //newAcc.AddKeyProperty(Name,(Guid)Val);
                                        break;
                                    case AttributeInternalType.UniqueIdentifier:
                                        break;
                                    case AttributeInternalType.Lookup:
                                        RetrieveLookup(newAcc,Name,(Guid)Val,val3,PrimaryFieldStringValue,val2);
                                        break;
                                    case AttributeInternalType.Owner:
                                        {
                                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts Owner Type: {0}",val2),Crm2CrmTrace.Sw.Info);
                                            string otp      =   (string)val2;
                                            FindOwner(otp,Name,newAcc,(Guid)Val,(string)val3);
                                        }
                                        break;
                                    default:
                                    if ( Crm2CrmTrace.Sw.TraceError )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm CopyAllAccounts missing column: [{0}]", Name),Crm2CrmTrace.Sw.Info);
                                    break;
                                }
                                return true;
                            }
                            );
                        _EntranceLevel--;
                        Guid PrimaryKeyValue    =   s.KeyPropertyValue(s.PrimaryKeyName);
                        Guid newPrimaryKeyValue =   Guid.Empty;
                        bool exists             =   DicDic[CrmStr.account].ContainsKey(PrimaryKeyValue);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts before create account name: {0}, exists: {1} ", newAcc.name,exists),Crm2CrmTrace.Sw.Info);
                        if (!exists && ( dup == null) )
                        {
                            newPrimaryKeyValue  =   newAcc.adminCreate();
                            CreateCount++;
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts Create Success for: [{0}], stateCode: {1}", newPrimaryKeyValue,stateCode), Crm2CrmTrace.Sw.Info);
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts Adding PrimaryKeyName: {0}, PrimaryKeyValue: {1} ", s.PrimaryKeyName,PrimaryKeyValue),Crm2CrmTrace.Sw.Info);
                            DicDic[CrmStr.account].Add(PrimaryKeyValue, newAcc);
                        }
                        else if (exists ) // must update because already created in a hurry
                        {
                            newAcc.EntityID     =   ((ADNDynAccount)DicDic[CrmStr.account][PrimaryKeyValue]).accountid;
                            newPrimaryKeyValue  =   newAcc.EntityID;
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts updating already created account name: {0}- id: {1}",
                                    newAcc.name, newAcc.EntityID), Crm2CrmTrace.Sw.Info);
                            newAcc.adminUpdate();
                            UpdateCount++;
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts Update Success for: [{0}], stateCode: {1}", newPrimaryKeyValue,stateCode), Crm2CrmTrace.Sw.Info);
                        }
                        else //  update dup
                        {
                            newAcc.EntityID     =   ((ADNDynAccount)dup).accountid;
                            newPrimaryKeyValue  =   newAcc.EntityID;
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts updating duplicate account name: {0}- id: {1}",
                                    newAcc.name, newAcc.EntityID), Crm2CrmTrace.Sw.Info);
                            newAcc.adminUpdate();
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts Update Success for: [{0}], stateCode: {1}", newPrimaryKeyValue,stateCode), Crm2CrmTrace.Sw.Info);
                        }
                        // Set State and Status code
                        if (stateCode != string.Empty)
                        {
                            int intState        =   Wrapper2.Util.StateCodeValueFromName(newAcc.SchemaName, stateCode);
                            Wrapper.Util.SetStateOperation(newAcc.SchemaName, newPrimaryKeyValue, intState, statusCode);
                        }
                    }
                    catch ( FatalException )
                    {
                        throw;
                    }
                    catch(InnerException ix)
                    {
                        _EntranceLevel          =   0;
                        if ( StopOnFirstError || MaxErrors <= TotErrorCount+(errCount) )
                            throw ix;
                    }
                    catch (CRMWrapperException sx)
                    {
                        _EntranceLevel          =   0;
                        string msg              =   string.Format("[E]Crm2Crm CopyAllAccounts i: {0}, ex: {1}",i, sx);
                        DicErrors.Add(string.Format("Copy Accounts failed for {0}.",s.name));
                        if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                            Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                        if ( ( sx.InnerException != null ) && ( sx.InnerException is System.Net.WebException ) )
                        {
                            System.Net.WebException ex2 =   (System.Net.WebException)sx.InnerException;
                            if ( ( ex2.InnerException != null ) && ( ex2.InnerException is System.Net.Sockets.SocketException ) )
                            {
                                msg = "[E]Crm2Crm CopyDynEntity Fatal sockets Exception";
                                if ( Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine(msg,( Crm2CrmTrace.Sw.TraceError ) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                                throw new FatalException(msg,sx);
                            }
                        }
                        if ( StopOnFirstError || MaxErrors <= TotErrorCount+(errCount++) )
                            throw new InnerException(msg,sx);
                    }
                    catch (Exception ex)
                    {
                        _EntranceLevel          =   0;
                        string msg              =   string.Format("[E]Crm2Crm CopyAllAccounts i: {0}, ex : {1}",i, ex);
                        DicErrors.Add(string.Format("Copy Accounts failed for {0}.",s.name));
                        if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                            Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                        if ( StopOnFirstError || MaxErrors <= TotErrorCount+(errCount++) )
                            throw new InnerException(msg,ex);
                    }
                }
            }
            catch ( FatalException )
            {
                throw;
            }
            catch(InnerException ix)
            {
                _EntranceLevel          =   0;
                TotErrorCount           +=  errCount;
                if ( StopOnFirstError || MaxErrors <= TotErrorCount )
                    throw ix;
            }
            catch (Exception ex)
            {
                _EntranceLevel          =   0;
                string msg              =   string.Format("[E]Crm2Crm CopyAllAccounts ex : {0}", ex);
                DicErrors.Add("Copy Accounts failed.");
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                TotErrorCount           +=  (++errCount);
                if ( StopOnFirstError || MaxErrors <= TotErrorCount )
                    throw new InnerException(msg,ex);
            }
            _EntranceLevel          =   0; // security
            if ( errCount > 0 )
                DicErrors.Add(string.Format("{0} errors count: {1}",CrmStr.account,errCount));
            DicOk.Add(CrmStr.account,new ResultCount(){ Copied=CreateCount, Created=CreateCount,Duplicates=DupCount,Updated=UpdateCount,Errors=errCount});

            TotErrorCount                                       +=  errCount;
            TotCreateCount                                      +=  CreateCount;
            TotDupCount                                         +=  DupCount;
            TotUpdCount                                         +=  UpdateCount;
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllAccounts END Count: {0}",count),Crm2CrmTrace.Sw.Info);
        }


        public void CopyAllContacts()
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts BEG FullCopy: {0}.",FullCopy),Crm2CrmTrace.Sw.Info);
            int count                                                   =   0;
            errCount                                                    =   0;
            CreateCount                                                 =   0;
            DupCount                                                    =   0;
            UpdateCount                                                 =   0;

            List<ADNDynContact> dynContacts2                            =   new List<ADNDynContact>();
            try
            {
                _entityName                                             =   CrmStr.contact;
                GenericDynQueryMultiple<ADNDynContact> allContactQuery  =   new GenericDynQueryMultiple<ADNDynContact>(Wrapper2,ResetWrapper,CrmStr.contact);
                InternalQueryExpression qe                              =   null;
                if ( ! FullCopy )
                {
                    DateTime startdate                                  =   (RadStartDate.SelectedDate.HasValue ) ? RadStartDate.SelectedDate.Value:CRMUtil.minDateTime;
                    string reqDate                                      =   string.Format(CultureInfo.InvariantCulture, "{0:s}",startdate);
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts startdate: {0}, reqDate: {1}.",startdate,reqDate),Crm2CrmTrace.Sw.Info);
                    qe                                                  =   new InternalQueryExpression();
                    qe.EntityName                                       =   CrmStr.contact;
                    InternalAllColumns RequestCols                      =   new InternalAllColumns();
                    InternalFilterExpression fi                         =   new InternalFilterExpression();
                    InternalConditionExpression ex                      =   new InternalConditionExpression();
                    ex.AttributeName                                    =   CrmStr.createdon;
                    ex.Operator                                         =   InternalConditionOperator.OnOrAfter;
                    ex.Values                                           =   new string[]{reqDate};
                    fi.Conditions                                       =   new InternalConditionExpression[]{ex};
                    qe.ColumnSet                                        =   RequestCols;
                    qe.Criteria                                         =   fi;
                }
                InternalBusinessEntityCollection allContact             =   allContactQuery.adminRetrieve(qe);
                _TConfig                                                =   null;
                _TConfig2                                               =   null;
                PropertyDescriptorCollection _columnDescriptors         =   null;
                Wrapper2.Util.ExecForEachDynamicEntity(allContact,
                    delegate(InternalDynamicEntity de)
                    {
                        ADNDynContact ob                                =   new ADNDynContact(Wrapper2, de, _columnDescriptors,null);
                        ob.EntityMData                                  =   TConfig2.entityMetaData;
                        _columnDescriptors                              =   ob.PropertyDescriptorCollection;
                        dynContacts2.Add(ob);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts after Ctor for DynEntity: {0}.", ob.SchemaName),Crm2CrmTrace.Sw.Info);
                        return true;
                    }
                    );
                count                                                   =   dynContacts2.Count;
                ProgressPrimCount++;
                ResetProgressSecTotal(count);
                SetUpdateProgress("Copy contacts starts",ProgressPrimCount,ProgressSecCount);
                for (int i = 0; i < count; i++)
                {
                    DynEntity s                                         =   dynContacts2[i];
                    DynEntity dup                                       =   null;
                    try
                    {
                        string PrimaryFieldStringValue                  =   s.PrimaryFieldStringValue;
                        SetUpdateProgress(string.Format("Contact '{0}'",PrimaryFieldStringValue),ProgressPrimCount,ProgressSecCount++);
                        ADNDynContact newAcc    =   null;
                        if (ShoudCheckDuplicates(CrmStr.contact))
                        {
                            if ( ExistDuplicates(s,PrimaryFieldStringValue,ref dup) && (dup.modifiedonLocalDate >= s.modifiedonLocalDate )) // we keep duplicates with modified value equal or more recent than org
                                continue;
                        }
                        newAcc                                          =   new ADNDynContact(Wrapper,s.StringPropertyValue(CrmStr.firstname),s.StringPropertyValue(CrmStr.lastname));
                        string stateCode                                =   string.Empty;
                        int statusCode                                  =   0;
                        _EntranceLevel++;

                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts i: {0}, PrimaryFieldStringValue: {1}",  i,PrimaryFieldStringValue ),Crm2CrmTrace.Sw.Info);
                        Wrapper2.Util.ExecForEachDynamicEntityProperty(s,
                            delegate(string Name,object Val,object val2,object val3,AttributeInternalType tp)
                            {
                                if (!TConfig.attributesDic.ContainsKey(Name))
                                {
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts Property not in V4 Name: {0}",Name),Crm2CrmTrace.Sw.Info);
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        for (int j = 0; j < TConfig.attributesDic.Count; j++)
                                        {
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm j: {0}, key: {1}",j,TConfig.attributesDic.Keys[j]),Crm2CrmTrace.Sw.Info);
                                        }
                                }
                                InternalAttributeMetadata attributeMetaData =   TConfig[Name];
                                bool ValidForCreate                     =   Wrapper.Util.ExtractAttributeFieldAsBool(attributeMetaData,InternalAttributeFields.ValidForCreate);
                                bool ValidForUpdate                     =   Wrapper.Util.ExtractAttributeFieldAsBool(attributeMetaData,InternalAttributeFields.ValidForUpdate);
                                if ( Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContact Name: {0}, ValidForCreate: {1}, ValidForUpdate: {2}.",Name,ValidForCreate,ValidForUpdate),Crm2CrmTrace.Sw.Info);
                                if (!ValidForCreate && !ValidForUpdate)
                                {
                                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts Not Valid For Create/Update Name: {0}",Name),Crm2CrmTrace.Sw.Info);
                                    if (Name.Equals(CrmStr.statecode))
                                    {
                                        stateCode   =   (string)Val;
                                        if (Crm2CrmTrace.Sw.TraceVerbose)
                                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContact stateCode for {0}: {1}", entityName, Val), Crm2CrmTrace.Sw.Info);
                                    }
                                    return true;
                                }
                                switch(tp)
                                {
                                    case AttributeInternalType.Float:
                                        if ( Val is double )
                                                newAcc.AddFloatProperty(Name,(double)Val);
                                        else    newAcc.AddFloatProperty(Name,(float)Val);
                                        break;
                                    case AttributeInternalType.Integer:
                                        newAcc.AddNumberProperty(Name,(int)Val);
                                        break;
                                    case AttributeInternalType.Status:
                                        if (Name.Equals(CrmStr.statuscode))
                                        {
                                            statusCode = (int)Val;
                                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContact statuscode for {0}: {1}", entityName, Val), Crm2CrmTrace.Sw.Info);
                                        }
                                        else
                                            newAcc.AddStatusProperty(Name, (int)Val);
                                        break;
                                    case AttributeInternalType.Picklist:
                                        newAcc.AddPicklistProperty(Name,(int)Val);
                                        break;
                                    case AttributeInternalType.Decimal:
                                        newAcc.AddDecimalProperty(Name,(decimal)Val);
                                        break;
                                    case AttributeInternalType.State:
                                        if (Name.Equals(CrmStr.statecode))
                                        {
                                            stateCode   =   (string)Val;
                                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContact stateCode for {0}: {1}", entityName, Val), Crm2CrmTrace.Sw.Info);
                                        }
                                        break;
                                    case AttributeInternalType.String:
                                        newAcc.AddStringProperty(Name,(string)Val);
                                        break;
                                    case AttributeInternalType.Memo:
                                        newAcc.AddStringProperty(Name,(string)Val);
                                        break;
                                    case AttributeInternalType.DateTime:
                                        newAcc.AddDateTimeProperty(Name,(string)Val);
                                        break;
                                    case AttributeInternalType.Money:
                                        newAcc.AddMoneyProperty(Name,(decimal)Val);
                                        break;
                                    case AttributeInternalType.Boolean:
                                        newAcc.AddBooleanProperty(Name,(bool)Val);
                                        break;
                                    case AttributeInternalType.PrimaryKey:
                                        break;
                                    case AttributeInternalType.UniqueIdentifier:
                                        break;
                                    case AttributeInternalType.Lookup:
                                        RetrieveLookup(newAcc,Name,(Guid)Val,val3,PrimaryFieldStringValue,val2);
                                        break;
                                    case AttributeInternalType.Customer:
                                        RetrieveCustomer(newAcc,Name,(Guid)Val,val2,val3);
                                        break;
                                    case AttributeInternalType.Owner:
                                        {
                                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts Owner Type: {0}",val2),Crm2CrmTrace.Sw.Info);
                                            string otp      =   (string)val2;
                                            FindOwner(otp,Name,newAcc,(Guid)Val,(string)val3);
                                            }
                                        break;
                                    default:
                                    if ( Crm2CrmTrace.Sw.TraceError )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm CopyAllContacts missing column: [{0}], Type: {1}", Name,tp),Crm2CrmTrace.Sw.Info);
                                    break;
                                }
                                return true;
                            }
                            );
                        _EntranceLevel--;
                        Guid PrimaryKeyValue    =   s.KeyPropertyValue(s.PrimaryKeyName);
                        Guid newPrimaryKeyValue =   Guid.Empty;
                        bool exists             =   DicDic[CrmStr.contact].ContainsKey(PrimaryKeyValue);
                        if ( Crm2CrmTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts before create lastname: {0}, exists: {1} ", newAcc.lastname,exists),Crm2CrmTrace.Sw.Info);
                        if (!exists && ( dup == null) )
                        {
                            newPrimaryKeyValue  =   newAcc.adminCreate();
                            CreateCount++;
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts Create Success for: [{0}], stateCode: {1}", newPrimaryKeyValue,stateCode), Crm2CrmTrace.Sw.Info);
                            if ( Crm2CrmTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts Adding to contact dic PrimaryKeyName: {0}, PrimaryKeyValue: {1} ", s.PrimaryKeyName,PrimaryKeyValue),Crm2CrmTrace.Sw.Info);
                            DicDic[CrmStr.contact].Add(PrimaryKeyValue, newAcc);
                        }
                        else if (exists )// must update because already created in a hurry
                        {
                            newAcc.EntityID     =   ((ADNDynContact)DicDic[CrmStr.contact][PrimaryKeyValue]).contactid;
                            newPrimaryKeyValue  =   newAcc.EntityID;
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts updating already created contact lastname: {0}, id: {1}", newAcc.lastname, newAcc.EntityID), Crm2CrmTrace.Sw.Info);
                            newAcc.adminUpdate();
                            UpdateCount++;
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts Update Success for: [{0}], stateCode: {1}", newPrimaryKeyValue,stateCode), Crm2CrmTrace.Sw.Info);
                        }
                        else //  update dup
                        {
                            newAcc.EntityID     =   ((ADNDynContact)dup).contactid;
                            newPrimaryKeyValue  =   newAcc.EntityID;
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts updating duplicate account name: {0}- id: {1}",
                                    newAcc.name, newAcc.EntityID), Crm2CrmTrace.Sw.Info);
                            newAcc.adminUpdate();
                            if (Crm2CrmTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts Update Success for: [{0}], stateCode: {1}", newPrimaryKeyValue,stateCode), Crm2CrmTrace.Sw.Info);
                        }
                        // Set State and Status code
                        if (stateCode != string.Empty)
                        {
                            int intState = Wrapper2.Util.StateCodeValueFromName(newAcc.SchemaName, stateCode);
                            Wrapper.Util.SetStateOperation(newAcc.SchemaName, newPrimaryKeyValue, intState,statusCode);
                        }
                    }
                    catch ( FatalException )
                    {
                        throw;
                    }
                    catch(InnerException ix)
                    {
                        _EntranceLevel          =   0;
                        if ( StopOnFirstError || MaxErrors <= TotErrorCount )
                            throw ix;
                    }
                    catch (CRMWrapperException sx)
                    {
                        _EntranceLevel          =   0;
                        string msg              =   string.Format("[E]Crm2Crm CopyAllContacts i: {0}, ex: {1}",i, sx);
                        DicErrors.Add(string.Format("Copy Contact failed for {0}.",s.fullname));
                        if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                            Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                        if ( ( sx.InnerException != null ) && ( sx.InnerException is System.Net.WebException ) )
                        {
                            System.Net.WebException ex2 =   (System.Net.WebException)sx.InnerException;
                            if ( ( ex2.InnerException != null ) && ( ex2.InnerException is System.Net.Sockets.SocketException ) )
                            {
                                msg             = "[E]Crm2Crm CopyDynEntity Fatal sockets Exception";
                                if ( Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine(msg,( Crm2CrmTrace.Sw.TraceError ) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                                throw new FatalException(msg,sx);
                            }
                        }

                        if ( StopOnFirstError || MaxErrors <= TotErrorCount+(errCount++) )
                            throw new InnerException(msg,sx);
                    }
                    catch (Exception ex)
                    {
                        _EntranceLevel          =   0;
                        string msg              =   string.Format("[E]Crm2Crm CopyAllContacts i: {0}, ex : {1}",i, ex);
                        DicErrors.Add(string.Format("Copy Contact failed for {0}.",s.fullname));
                        if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                            Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                        if ( StopOnFirstError || MaxErrors <= TotErrorCount+(errCount++) )
                            throw new InnerException(msg,ex);
                    }
                }
            }
            catch ( FatalException )
            {
                throw;
            }
            catch(InnerException ix)
            {
                _EntranceLevel          =   0;
                TotErrorCount           +=  errCount;
                if ( StopOnFirstError || MaxErrors <= TotErrorCount )
                    throw ix;
            }
            catch (Exception ex)
            {
                _EntranceLevel          =   0;
                string msg              =   string.Format("[E]Crm2Crm CopyAllContacts ex : {0}", ex);
                DicErrors.Add("Copy Contacts failed");
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( msg,(Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                TotErrorCount           +=  (++errCount);
                if ( StopOnFirstError || MaxErrors <= TotErrorCount )
                    throw new InnerException(msg,ex);
                throw;
            }
            _EntranceLevel          =   0; // security
            if ( errCount > 0 )
                DicErrors.Add(string.Format("{0} errors count: {1}",CrmStr.contact,errCount));
            DicOk.Add(CrmStr.contact,new ResultCount(){ Copied=CreateCount, Created=CreateCount,Duplicates=DupCount,Updated=UpdateCount,Errors=errCount});

            TotErrorCount                                       +=  errCount;
            TotCreateCount                                      +=  CreateCount;
            TotDupCount                                         +=  DupCount;
            TotUpdCount                                         +=  UpdateCount;
            if (Crm2CrmTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CopyAllContacts END Count: {0}",count),Crm2CrmTrace.Sw.Info);
        }

        /* Entites supporting QueryMultiple
*account TargetRetrieveAccount 
*activitypointer TargetRetrieveActivityPointer 
*annotation TargetRetrieveAnnotation 
*appointment TargetRetrieveAppointment 
*calendar TargetRetrieveCalendar 
*campaign TargetRetrieveCampaign 
*campaignactivity TargetRetrieveCampaignActivity 
*campaignresponse TargetRetrieveCampaignResponse 
*competitor TargetRetrieveCompetitor 
*contact TargetRetrieveContact 
*contract TargetRetrieveContract 
*contractdetail TargetRetrieveContractDetail 
*contracttemplate TargetRetrieveContractTemplate 
*customeraddress TargetRetrieveCustomerAddress 
*customeropportunityrole TargetRetrieveCustomerOpportunityRole 
*customerrelationship TargetRetrieveCustomerRelationship 
*discount TargetRetrieveDiscount 
*discounttype TargetRetrieveDiscountType 
*email TargetRetrieveEmail 
*equipment TargetRetrieveEquipment 
*fax TargetRetrieveFax 
*incident TargetRetrieveIncident 
*incidentresolution TargetRetrieveIncidentResolution 
*invoice TargetRetrieveInvoice 
*invoicedetail TargetRetrieveInvoiceDetail 
*kbarticle TargetRetrieveKbArticle 
*kbarticlecomment TargetRetrieveKbArticleComment 
*kbarticletemplate TargetRetrieveKbArticleTemplate 
*lead TargetRetrieveLead 
*letter TargetRetrieveLetter 
*list TargetRetrieveList 
*opportunity TargetRetrieveOpportunity 
*opportunityclose TargetRetrieveOpportunityClose 
*opportunityproduct TargetRetrieveOpportunityProduct 
*orderclose TargetRetrieveOrderClose 
*phonecall TargetRetrievePhoneCall 
*pricelevel TargetRetrievePriceLevel 
*product TargetRetrieveProduct 
*productpricelevel TargetRetrieveProductPriceLevel 
*quote TargetRetrieveQuote 
*quoteclose TargetRetrieveQuoteClose 
*quotedetail TargetRetrieveQuoteDetail 
*relationshiprole TargetRetrieveRelationshipRole 
*relationshiprolemap TargetRetrieveRelationshipRoleMap 
*resource TargetRetrieveResource 
*resourcegroup TargetRetrieveResourcesGroup 
*resourcespec TargetRetrieveResourcesSpec 
role TargetRetrieveRole 
*salesliterature TargetRetrieveSalesLiterature 
*salesliteratureitem TargetRetrieveSalesLiteratureItem 
*salesorder TargetRetrieveSalesOrder 
*salesorderdetail TargetRetrieveSalesOrderDetail 
*service TargetRetrieveService 
*serviceappointment TargetRetrieveServiceAppointment 
*site TargetRetrieveSite 
*subject TargetRetrieveSubject 
*task TargetRetrieveTask 
*template TargetRetrieveTemplate 
*territory TargetRetrieveTerritory 
*uom TargetRetrieveUoM 
*uomschedule TargetRetrieveUoMSchedule 

*annualfiscalcalendar TargetRetrieveAnnualFiscalCalendar 
*fixedmonthlyfiscalcalendar TargetRetrieveFixedMonthlyFiscalCalendar 
*monthlyfiscalcalendar TargetRetrieveMonthlyFiscalCalendar 
*quarterlyfiscalcalendar TargetRetrieveQuarterlyFiscalCalendar 
*semiannualfiscalcalendar TargetRetrieveSemiAnnualFiscalCalendar 

*team TargetRetrieveTeam 

userquery TargetRetrieveUserQuery 
savedquery TargetRetrieveSavedQuery 

bulkdeleteoperation TargetRetrieveBulkDeleteOperation 
bulkdeletefailure TargetRetrieveBulkDeleteFailure 
businessunit TargetRetrieveBusinessUnit 
businessunitnewsarticle TargetRetrieveBusinessUnitNewsArticle 
constraintbasedgroup TargetRetrieveConstraintBasedGroup 
duplicaterecord TargetRetrieveDuplicateRecord 
duplicaterule TargetRetrieveDuplicateRule 
duplicaterulecondition TargetRetrieveDuplicateRuleCondition 
import TargetRetrieveImport 
importfile TargetRetrieveImportFile 
importlog TargetRetrieveImportLog 
importmap TargetRetrieveImportMap 
plugintype TargetRetrievePluginType 
queue TargetRetrieveQueue 
queueitem TargetRetrieveQueueItem 
systemuser TargetRetrieveSystemUser 
         */
        void Crm2Crm_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm Crm2Crm_ADNUpdateModule BEG IsInAsyncPostBack: {0}.", IsInAsyncPostBack), Crm2CrmTrace.Sw.Info);
            ProgressPrimaryTotal                =   0;
            ProgressTotalSteps                  =   0;

            if (CbCustomers.Checked)
                ProgressPrimaryTotal            =   5;
            if (CbCustomerRelations.Checked)
                 ProgressPrimaryTotal           +=  6;
            if (CbProducts.Checked)
                 ProgressPrimaryTotal           +=  7;
            if (CbOpportunities.Checked)
                 ProgressPrimaryTotal           +=  3;
            if (CbQuotes.Checked)
                 ProgressPrimaryTotal           +=  3;
            if (CbOrders.Checked)
                 ProgressPrimaryTotal           +=  3;
            if (CbInvoices.Checked)
                 ProgressPrimaryTotal           +=  2;
            if (CbActivities.Checked)
                 ProgressPrimaryTotal           +=  7;
            if (CbLists.Checked)
                 ProgressPrimaryTotal           +=  2;
            if (CbCampaigns.Checked)
                 ProgressPrimaryTotal           +=  3;
            if ( CbContracts.Checked )
                 ProgressPrimaryTotal           +=  3;
            if ( CbCalendar.Checked )
                 ProgressPrimaryTotal           +=  6;
            if ( CbService.Checked )
                 ProgressPrimaryTotal           +=  11;
            // start progress count
            StartProgress();
            
            bool    Fatal                       =   false;
            
            DateTime stDate                     =   DateTime.Now;
            try
            {
                ReadMappings();
                InitBusinessUnits();
                // to avoid  a second click
                updateBtn.Visible               =   false;
                resetBtn.Visible                =   true;
                LabelSummary.Text               =   LocalizeHelper.Localize("CRM2CRM_EXECSUMMARY","Result summary");
                DicDic.Add(CrmStr.account,new DicDynEnt());
                DicDic.Add(CrmStr.contact,new DicDynEnt());
                DicDic.Add(CrmStr.lead,new DicDynEnt());
                DicDic.Add(CrmStr.product,new DicDynEnt());
                if ( !DicDic.ContainsKey(CrmStr.systemuser) )
                {
                    DicDynEnt dic               =   new DicDynEnt();
                    DicDic.Add(CrmStr.systemuser, dic);
                }

                if (CbCustomers.Checked)
                {
                    _entityName                 =   CrmStr.account;
                    CopyAllAccounts();
                    _entityName                 =   CrmStr.contact;
                    CopyAllContacts();
                    _entityName                 =   CrmStr.lead;
                    CopyAll();
                    _entityName                 =   CrmStr.customeraddress;
                    CopyAll();
                    _entityName                 =   CrmStr.competitor;
                    CopyAll();
                    _entityName                 =   CrmStr.territory;
                    CopyAll();
                    _entityName                 =   CrmStr.team;
                    CopyAll();
                }
                else cbDefaultCheckDup.Checked  =   true; // if we dont create customers, force duplicate checking

                if (CbCustomerRelations.Checked)
                {
                    _entityName                 =   CrmStr.relationshiprolemap;
                    CopyAll();
                    _entityName                 =   CrmStr.relationshiprole;
                    CopyAll();
                    _entityName                 =   CrmStr.customerrelationship;
                    CopyAll();
                    _entityName                 =   CrmStr.subject;
                    CopyAll();
                }
                if (CbProducts.Checked)
                {
                    _entityName                 =   CrmStr.uom; // must stay before uomschedule
                    CopyAll();
                    _entityName                 =   CrmStr.uomschedule;
                    CopyAll();
                    _entityName                 =   CrmStr.discounttype;
                    CopyAll();
                    _entityName                 =   CrmStr.discount;
                    CopyAll();
                    _entityName                 =   CrmStr.pricelevel;
                    CopyAll();
                    _entityName                 =   CrmStr.product;
                    CopyAll();
                    //We should have already copied all these implied
                    _entityName                 =   CrmStr.productpricelevel;
                    CopyAll();
                }
                if (CbOpportunities.Checked)
                {
                    _entityName                 =   CrmStr.opportunity;
                    CopyAll();
                    _entityName                 =   CrmStr.customeropportunityrole;
                    CopyAll();
                    _entityName                 =   CrmStr.opportunityproduct;
                    CopyAll();
                    if (NeedOpportunityClose)
                    {
                        _entityName             =   CrmStr.opportunityclose;
                        CopyAll();
                    }
                    else
                    {
                        ProgressPrimaryTotal    +=  1;
                        SetUpdateProgress(string.Empty,ProgressPrimCount,ProgressSecCount);
                    }

                }
                if (CbQuotes.Checked)
                {
                    _entityName                 =   CrmStr.quote;
                    CopyAll();
                    _entityName                 =   CrmStr.quotedetail;
                    CopyAll();
                    if (NeedQuoteClose)
                    {
                        _entityName             =   CrmStr.quoteclose;
                        CopyAll();
                    }
                    else
                    {
                        ProgressPrimaryTotal    +=  1;
                        SetUpdateProgress(string.Empty,ProgressPrimCount,ProgressSecCount);
                    }
                }
                if (CbOrders.Checked)
                {
                    _entityName                 =   CrmStr.salesorder;
                    CopyAll();
                    _entityName                 =   CrmStr.salesorderdetail;
                    CopyAll();
                    if (NeedOrderClose)
                    {
                        _entityName             =   CrmStr.orderclose;
                        CopyAll();
                    }
                    else
                    {
                        ProgressPrimaryTotal    +=  1;
                        SetUpdateProgress(string.Empty,ProgressPrimCount,ProgressSecCount);
                    }
                }
                if (CbInvoices.Checked)
                {
                    _entityName     =   CrmStr.invoice;
                    CopyAll();
                    _entityName     =   CrmStr.invoicedetail;
                    CopyAll();
                }
                // Do it after all entities subjevct to a relation
                if (CbCustomerRelations.Checked)
                {
                    _entityName     =   CrmStr.salesliterature;
                    CopyAll();
                    _entityName     =   CrmStr.salesliteratureitem; //appears as Document in UI
                    CopyAll();
                }
                if (CbActivities.Checked)
                {
                    _entityName     =   CrmStr.task;
                    CopyAll();
                    _entityName     =   CrmStr.phonecall;
                    CopyAll();
                    _entityName     =   CrmStr.appointment;
                    CopyAll();
                    _entityName     =   CrmStr.letter;
                    CopyAll();
                    _entityName     =   CrmStr.email;
                    CopyAll();
                    // we must check for dup here
                    _entityName     =   CrmStr.template;
                    CopyAll();
                    _entityName     =   CrmStr.fax;
                    CopyAll();
                    _entityName     =   CrmStr.annotation;
                    CopyAll();
                }
                if (CbLists.Checked)
                {
                    _entityName = CrmStr.list;
                    CopyAll();
                }
                if (CbCampaigns.Checked)
                {
                    _entityName = CrmStr.campaign;
                    CopyAll();
                    _entityName = CrmStr.campaignactivity;
                    CopyAll();
                    _entityName = CrmStr.campaignresponse;
                    CopyAll();
                }
                if ( CbContracts.Checked )
                {
                    _entityName = CrmStr.contracttemplate;
                    CopyAll();
                    _entityName = CrmStr.contract;
                    CopyAll();
                    _entityName = CrmStr.contractdetail;
                    CopyAll();
                }
                if ( CbCalendar.Checked )
                {
                    _entityName = CrmStr.calendar;
                    CopyAll();
                    _entityName = CrmStr.annualfiscalcalendar;
                    CopyAll();
                    _entityName = CrmStr.fixedmonthlyfiscalcalendar;
                    CopyAll();
                    _entityName = CrmStr.monthlyfiscalcalendar;
                    CopyAll();
                    _entityName = CrmStr.quarterlyfiscalcalendar;
                    CopyAll();
                    _entityName = CrmStr.semiannualfiscalcalendar;
                    CopyAll();
                }
                if ( CbService.Checked )
                {
                    _entityName = CrmStr.site;
                    CopyAll();
                    _entityName = CrmStr.equipment;
                    CopyAll();
                    _entityName = CrmStr.constraintbasedgroup;
                    CopyAll();
                    _entityName = CrmStr.resourcespec;
                    CopyAll();
                    _entityName = CrmStr.service;
                    CopyAll();
                    _entityName = CrmStr.incident;
                    CopyAll();
                    _entityName = CrmStr.incidentresolution;
                    CopyAll();
                    _entityName = CrmStr.kbarticle;
                    CopyAll();
                    _entityName = CrmStr.kbarticlecomment; 
                    CopyAll();
                    _entityName = CrmStr.kbarticletemplate;
                    CopyAll();
                    _entityName = CrmStr.serviceappointment;
                    CopyAll();
                }
                string customLst    =   RadLbCustomEnt.SelectedValue;
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm Crm2Crm_ADNUpdateModule customLst: {0}.", customLst), Crm2CrmTrace.Sw.Info);
                string[] Customs    =   customLst.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
                foreach ( string custEnt in Customs )
                {
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm Crm2Crm_ADNUpdateModule custEnt: {0}.", custEnt), Crm2CrmTrace.Sw.Info);
                    _entityName = custEnt;
                    CopyAll();
                }
            }
            catch (FatalException fx)
            {
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm Crm2Crm_ADNUpdateModule fx :{0}", fx), (Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                e.Cancel                =   true;
                Fatal                   =   true;
            }
            catch (Exception ex)
            {
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm Crm2Crm_ADNUpdateModule ex :{0}", ex), (Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                e.Cancel                =   true;
            }
            finally
            {
                EndProgress();
                Literal Summary         =   new Literal();
                StringBuilder sb        =   new StringBuilder();
                string fmt              =   string.Empty;
                if ( Fatal )
                {
                    fmt                 =   LocalizeHelper.Localize("CRM2CRM_FATALERR","<strong>Socket Error, check your server parameters according KB.</strong>.<br /><br />");
                    sb.Append(fmt);
                }
                fmt                     =   LocalizeHelper.Localize("CRM2CRM_EXECSUM1","<strong>Execution summary:</strong><br/>Source Server: {0}, Crm Version: {1},Organization: {2}<br />");
                sb.AppendFormat(fmt,new object[]{Wrapper2.CrmServiceUrl,Wrapper2.CrmVersion,Wrapper2.OrganizationFriendlyName});
                fmt                     =   LocalizeHelper.Localize("CRM2CRM_EXECSUM2","Destination Server: {0}, Crm Version: {1},Organization: {2}<br />");
                sb.AppendFormat(fmt,new object[]{Wrapper.CrmServiceUrl,Wrapper.CrmVersion,Wrapper.OrganizationFriendlyName});
                if ( DicErrors.Count > 0 )
                {
                    fmt                 =   LocalizeHelper.Localize("CRM2CRM_EXECSUM4","<br /><strong>End with {0} errors:</strong><br/>");
                    sb.AppendFormat(fmt,DicErrors.Count);
                }
                else
                {
                    fmt                 =   LocalizeHelper.Localize("CRM2CRM_EXECSUM5","<br /><strong>End with no errors.</strong><br/>");
                    sb.Append(fmt);
                }
                foreach ( string key in DicErrors )
                {
                    sb.AppendFormat("{0}<br />",key);
                }
                fmt                     =   LocalizeHelper.Localize("CRM2CRM_EXECSUM3","Total Copied: {0}<br />Total Duplicates: {1}<br />Total Updated: {2}<br />Start At: {3}.<br />End At: {4}.<br /><br />");
                sb.AppendFormat(fmt,new object[]{TotCreateCount,TotDupCount,TotUpdCount,stDate,DateTime.Now});
                Summary.Text            =   sb.ToString();
                RadTbSummary.Controls.Add(Summary);
                ReportResult();
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm Crm2Crm_ADNUpdateModule END.",Crm2CrmTrace.Sw.Info);
        }
        
        /// <summary>
        /// Utility if chekenable for entityu returns "(*)" else empty string
        /// </summary>
        string UCheckDuplicates(string schema)
        {
            return CheckDuplicates(schema) ? "*":string.Empty ;
        }

        int totRecords          =   0;
        int FetchCount(CRMWrapperBase Wrap,string schemaName,string PrimaryKey)
        {
            int cnt             =   0;
            try
            {
                cnt             =   Wrap.FetchCount(schemaName,PrimaryKey,string.Empty,true);
                if ( Wrap != Wrapper )
                {
                    Records.Add(schemaName,cnt);
                    totRecords += cnt;
                }
            }
            catch (Exception ex)
            {
                if (Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm FetchCount {0}, schemaName: {1}, PrimKey: {2}, ex: {3}",(Wrap == Wrapper) ? "Dest":"Source",schemaName,PrimaryKey,ex),Crm2CrmTrace.Sw.Info);
                return -1;
            }

            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FetchCount {0} schemaName: {2}, Count: {2}.",(Wrap == Wrapper) ? "Dest":"Source",schemaName,cnt),Crm2CrmTrace.Sw.Info);
            return cnt;
        }

        void AddCell(Table tb,string schemaName,string primKey,bool addTb)
        {
            TableRow tr     =   tb.Rows[tb.Rows.Count-1];
            if ( !addTb )
                tr          =   new TableRow();
            TableCell c     =   new TableCell();
            c.Text          =   schemaName;
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   FetchCount(Wrapper2,schemaName,primKey).ToString();
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   FetchCount(Wrapper,schemaName,primKey).ToString();
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
        }
        
        void FillRow(Table tb)
        {
            TableRow tr     =   tb.Rows[tb.Rows.Count-1];
            TableCell c     =   new TableCell();
            tr.Cells.Add(c);
            c               =   new TableCell();
            tr.Cells.Add(c);
            c               =   new TableCell();
            tr.Cells.Add(c);
        }

        /// <summary>
        /// Read the entities to copy from source, when copy all
        /// </summary>
        void  ReadCounts()
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm ReadCounts BEG.", Crm2CrmTrace.Sw.Info);
            totRecords          =   0;
            try
            {
                Table tb        =   new Table();
                tb.CellPadding  =   2;
                tb.CellSpacing  =   0;
                tb.BorderColor  =   Color.Black;
                tb.BorderWidth  =   new Unit(1);
                tb.GridLines    =   GridLines.Both;
                tb.HorizontalAlign  =    HorizontalAlign.Center;
                TableRow tr     =   new TableRow();
                tr.BackColor    =   Color.Gray;
                TableCell c     =   new TableCell();
                c.Text          =   "<strong>Entity</strong>";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "<strong>Src Count</strong>";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "<strong>Dest Count</strong>";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "<strong>Entity</strong>";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "<strong>Src Count</strong>";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "<strong>Dest Count</strong>";
                tr.Cells.Add(c);
                tb.Rows.Add(tr);

                if (CbCustomers.Checked)
                {
                    AddCell(tb,CrmStr.account,CrmStr.accountid,false);
                    AddCell(tb,CrmStr.contact,CrmStr.contactid,true);
                    AddCell(tb,CrmStr.lead,CrmStr.leadid,false);
                    AddCell(tb,CrmStr.customeraddress,CrmStr.customeraddressid,true);
                    AddCell(tb,CrmStr.competitor,CrmStr.competitorid,false);
                    AddCell(tb,CrmStr.relationshiprole,CrmStr.relationshiproleid,true);
                    AddCell(tb,CrmStr.relationshiprolemap,CrmStr.relationshiprolemapid,false);
                    FillRow(tb);
                }
                if (CbProducts.Checked)
                {
                    AddCell(tb,CrmStr.uom,CrmStr.uomid,false);
                    AddCell(tb,CrmStr.uomschedule,CrmStr.uomscheduleid,true);
                    AddCell(tb,CrmStr.discounttype,CrmStr.discounttypeid,false);
                    AddCell(tb,CrmStr.discount,CrmStr.discountid,true);
                    AddCell(tb,CrmStr.pricelevel,CrmStr.pricelevelid,false);
                    AddCell(tb,CrmStr.product,CrmStr.productid,true);
                    AddCell(tb,CrmStr.productpricelevel,CrmStr.productpricelevelid,false);
                    FillRow(tb);
                }
                if (CbOpportunities.Checked)
                {
                    AddCell(tb,CrmStr.opportunity,CrmStr.opportunityid,false);
                    FillRow(tb);
                }
                if (CbQuotes.Checked)
                {
                    AddCell(tb,CrmStr.quote,CrmStr.quoteid,false);
                    FillRow(tb);
                }
                if (CbOrders.Checked)
                {
                    AddCell(tb,CrmStr.salesorder,CrmStr.salesorderid,false);
                    FillRow(tb);
                }
                if (CbInvoices.Checked)
                {
                    AddCell(tb,CrmStr.invoice,CrmStr.invoiceid,false);
                    FillRow(tb);
                }
                if (CbActivities.Checked)
                {
                    AddCell(tb,CrmStr.task,CrmStr.activityid,false);
                    AddCell(tb,CrmStr.phonecall,CrmStr.activityid,true);
                    AddCell(tb,CrmStr.appointment,CrmStr.activityid,false);
                    AddCell(tb,CrmStr.letter,CrmStr.activityid,true);
                    AddCell(tb,CrmStr.email,CrmStr.activityid,false);
                    AddCell(tb,CrmStr.annotation,CrmStr.annotationid,true);
                }
                if (CbLists.Checked)
                {
                    AddCell(tb,CrmStr.list,CrmStr.listid,false);
                    FillRow(tb);
                }
                if (CbCampaigns.Checked)
                {
                    AddCell(tb,CrmStr.campaign,CrmStr.campaignid,false);
                    AddCell(tb,CrmStr.campaignactivity,CrmStr.activityid,true);
                    AddCell(tb,CrmStr.campaignresponse,CrmStr.activityid,false);
                    FillRow(tb);
                }
                if ( CbContracts.Checked )
                {
                    AddCell(tb,CrmStr.contracttemplate,CrmStr.contracttemplateid,false);
                    AddCell(tb,CrmStr.contract,CrmStr.contractid,true);
                    AddCell(tb,CrmStr.contractdetail,CrmStr.contractdetailid,false);
                    FillRow(tb);
                }
                if ( CbCalendar.Checked )
                {
                    AddCell(tb,CrmStr.calendar,CrmStr.calendarid,false);
                    AddCell(tb,CrmStr.annualfiscalcalendar,CrmStr.userfiscalcalendarid,true);
                    AddCell(tb,CrmStr.fixedmonthlyfiscalcalendar,CrmStr.userfiscalcalendarid,false);
                    AddCell(tb,CrmStr.monthlyfiscalcalendar,CrmStr.userfiscalcalendarid,true);
                    AddCell(tb,CrmStr.quarterlyfiscalcalendar,CrmStr.userfiscalcalendarid,false);
                    AddCell(tb,CrmStr.semiannualfiscalcalendar,CrmStr.userfiscalcalendarid,true);
                }
                if ( CbService.Checked )
                {
                    AddCell(tb,CrmStr.site,CrmStr.siteid,false);
                    AddCell(tb,CrmStr.resource,CrmStr.resourceid,true);
                    AddCell(tb,CrmStr.service,CrmStr.serviceid,false);
                    AddCell(tb,CrmStr.incident,CrmStr.incidentid,true);
                    AddCell(tb,CrmStr.serviceappointment,CrmStr.activityid,false);
                    FillRow(tb);
                }
                string customLst        =   RadLbCustomEnt.SelectedValue;
                string[] Customs        =   customLst.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
                bool oddrw              =   false;
                foreach ( string custEnt in Customs )
                {
                    DynEntity custDyn   =   new DynEntity(Wrapper2,custEnt);
                    string primKey      =   custDyn.PrimaryKeyName; // heavy
                    AddCell(tb,custEnt,primKey,oddrw);
                    oddrw               =   !oddrw;
                }
                if ( oddrw )
                    FillRow(tb);
                tr              =   new TableRow();
                c               =   new TableCell();
                c.Text          =   "<strong>Total</strong>";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   string.Format("<strong>{0}</strong>",totRecords);
                tr.Cells.Add(c);
                tb.Rows.Add(tr);
                FillRow(tb);
                LbCounts.Controls.Add(tb);
                //force saving in viewstate
                Records         =   _Records;
            }
            catch (SoapException sex)
            {
                if (Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm ReadCounts soap ex :{0}", sex), Crm2CrmTrace.Sw.Info);
                LbCounts.Controls.Add(new LiteralControl(sex.Detail.InnerText));
            }
            catch (Exception ex)
            {
                if (Crm2CrmTrace.Sw.TraceError || Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm ReadCounts ex :{0}", ex), (Crm2CrmTrace.Sw.TraceError) ? Crm2CrmTrace.Sw.Info : Crm2CrmTrace.Sw.Info);
                throw;
            }
        }

        void AddCell2(Table tb,string schemaName,string primKey,bool addTb)
        {
            TableRow tr     =   tb.Rows[tb.Rows.Count-1];
            if ( !addTb )
                tr          =   new TableRow();
            TableCell c     =   new TableCell();
            c.Text          =   schemaName;
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   UCheckDuplicates(schemaName);
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   Records[schemaName].ToString();
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
        }
        
        void FillRow2(Table tb)
        {
            TableRow tr     =   tb.Rows[tb.Rows.Count-1];
            TableCell c     =   new TableCell();
            tr.Cells.Add(c);
            c               =   new TableCell();
            tr.Cells.Add(c);
            c               =   new TableCell();
            tr.Cells.Add(c);
        }
        /// <summary>
        ///  Fill Summary Text before execution
        /// </summary>
        void ReadData()
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm ReadData BEG.", Crm2CrmTrace.Sw.Info);
            Literal Intro       =   new Literal();
            StringBuilder sb    =   new StringBuilder();
            string fmt          =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM1","Source: {1} Organization {0}{1}");
            sb.AppendFormat(fmt,Wrapper2.OrganizationName,StStr.strBr);
            fmt                 =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM2","Fullname Format {0}{1}");
            sb.AppendFormat(fmt,Wrapper2.FullNameFormatName,StStr.strBr);
            fmt                 =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM3","CRM version {0}{1}{1}");
            sb.AppendFormat(fmt,Wrapper2.CrmVersion,StStr.strBr);

            fmt                 =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM4","Target: {1} Organization {0}{1}");
            sb.AppendFormat(fmt,Wrapper.OrganizationName,StStr.strBr);
            fmt                 =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM2","Fullname Format {0}{1}");
            sb.AppendFormat(fmt,Wrapper.FullNameFormatName,StStr.strBr);
            fmt                 =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM3","CRM version {0}{1}{1}");
            sb.AppendFormat(fmt,Wrapper.CrmVersion,StStr.strBr);
            
            fmt                 =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM5","Entities to copy:{0}");
            sb.AppendFormat(fmt,StStr.strBr);
            Intro.Text          =   sb.ToString();
            RadTbSummary.Controls.Add(Intro);
            
            Table tb            =   new Table();
            tb.CellPadding      =   2;
            tb.CellSpacing      =   0;
            tb.BorderColor      =   Color.Black;
            tb.BorderWidth      =   new Unit(1);
            tb.GridLines        =   GridLines.Both;
            tb.HorizontalAlign  =    HorizontalAlign.Center;
            TableRow tr         =   new TableRow();
            tr.BackColor        =   Color.Gray;
            TableCell c         =   new TableCell();
            c.Text              =   "<strong>Entity</strong>";
            tr.Cells.Add(c);
            c                   =   new TableCell();
            c.Text              =   "<strong>Duplicates</strong>";
            tr.Cells.Add(c);
            c                   =   new TableCell();
            c.Text              =   "<strong>Count</strong>";
            tr.Cells.Add(c);
            c                   =   new TableCell();
            c.Text              =   "<strong>Entity</strong>";
            tr.Cells.Add(c);
            c                   =   new TableCell();
            c.Text              =   "<strong>Duplicates</strong>";
            tr.Cells.Add(c);
            c                   =   new TableCell();
            c.Text              =   "<strong>Count</strong>";
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
            if (CbCustomers.Checked)
            {
                AddCell2(tb,CrmStr.account,CrmStr.accountid,false);
                AddCell2(tb,CrmStr.contact,CrmStr.contactid,true);
                AddCell2(tb,CrmStr.lead,CrmStr.leadid,false);
                AddCell2(tb,CrmStr.customeraddress,CrmStr.customeraddressid,true);
                AddCell2(tb,CrmStr.competitor,CrmStr.competitorid,false);
                AddCell2(tb,CrmStr.relationshiprole,CrmStr.relationshiproleid,true);
                AddCell2(tb,CrmStr.relationshiprolemap,CrmStr.relationshiprolemapid,false);
                FillRow2(tb);
            }
            if (CbProducts.Checked)
            {
                AddCell2(tb,CrmStr.uom,CrmStr.uomid,false);
                AddCell2(tb,CrmStr.uomschedule,CrmStr.uomscheduleid,true);
                AddCell2(tb,CrmStr.discounttype,CrmStr.discounttypeid,false);
                AddCell2(tb,CrmStr.discount,CrmStr.discountid,true);
                AddCell2(tb,CrmStr.pricelevel,CrmStr.pricelevelid,false);
                AddCell2(tb,CrmStr.product,CrmStr.productid,true);
                AddCell2(tb,CrmStr.productpricelevel,CrmStr.productpricelevelid,false);
                FillRow2(tb);
            }
            if (CbOpportunities.Checked)
            {
                AddCell2(tb,CrmStr.opportunity,CrmStr.opportunityid,false);
                FillRow2(tb);
            }
            if (CbQuotes.Checked)
            {
                AddCell2(tb,CrmStr.quote,CrmStr.quoteid,false);
                FillRow2(tb);
            }
            if (CbOrders.Checked)
            {
                AddCell2(tb,CrmStr.salesorder,CrmStr.salesorderid,false);
                FillRow2(tb);
            }
            if (CbInvoices.Checked)
            {
                AddCell2(tb,CrmStr.invoice,CrmStr.invoiceid,false);
                FillRow2(tb);
            }
            if (CbActivities.Checked)
            {
                AddCell2(tb,CrmStr.task,CrmStr.activityid,false);
                AddCell2(tb,CrmStr.phonecall,CrmStr.activityid,true);
                AddCell2(tb,CrmStr.appointment,CrmStr.activityid,false);
                AddCell2(tb,CrmStr.letter,CrmStr.activityid,true);
                AddCell2(tb,CrmStr.email,CrmStr.activityid,false);
                AddCell2(tb,CrmStr.annotation,CrmStr.annotationid,true);
            }
            if (CbLists.Checked)
            {
                AddCell2(tb,CrmStr.list,CrmStr.listid,false);
                FillRow2(tb);
            }
            if (CbCampaigns.Checked)
            {
                AddCell2(tb,CrmStr.campaign,CrmStr.campaignid,false);
                AddCell2(tb,CrmStr.campaignactivity,CrmStr.activityid,true);
                AddCell2(tb,CrmStr.campaignresponse,CrmStr.activityid,false);
                FillRow2(tb);
            }
            if ( CbContracts.Checked )
            {
                AddCell2(tb,CrmStr.contracttemplate,CrmStr.contracttemplateid,false);
                AddCell2(tb,CrmStr.contract,CrmStr.contractid,true);
                AddCell2(tb,CrmStr.contractdetail,CrmStr.contractdetailid,false);
                FillRow2(tb);
            }
            if ( CbCalendar.Checked )
            {
                AddCell2(tb,CrmStr.calendar,CrmStr.calendarid,false);
                AddCell2(tb,CrmStr.annualfiscalcalendar,CrmStr.userfiscalcalendarid,true);
                AddCell2(tb,CrmStr.fixedmonthlyfiscalcalendar,CrmStr.userfiscalcalendarid,false);
                AddCell2(tb,CrmStr.monthlyfiscalcalendar,CrmStr.userfiscalcalendarid,true);
                AddCell2(tb,CrmStr.quarterlyfiscalcalendar,CrmStr.userfiscalcalendarid,false);
                AddCell2(tb,CrmStr.semiannualfiscalcalendar,CrmStr.userfiscalcalendarid,true);
            }
            if ( CbService.Checked )
            {
                AddCell2(tb,CrmStr.site,CrmStr.siteid,false);
                AddCell2(tb,CrmStr.resource,CrmStr.resourceid,true);
                AddCell2(tb,CrmStr.service,CrmStr.serviceid,false);
                AddCell2(tb,CrmStr.incident,CrmStr.incidentid,true);
                AddCell2(tb,CrmStr.serviceappointment,CrmStr.activityid,false);
                FillRow2(tb);
            }
            string customLst        =   RadLbCustomEnt.SelectedValue;
            string[] Customs        =   customLst.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
            bool oddrw              =   false;
            foreach ( string custEnt in Customs )
            {
                DynEntity custDyn   =   new DynEntity(Wrapper2,custEnt);
                string primKey      =   custDyn.PrimaryKeyName; // heavy
                AddCell2(tb,custEnt,primKey,oddrw);
                oddrw               =   !oddrw;
            }
            if ( oddrw )
                FillRow2(tb);
            tr              =   new TableRow();
            tr.BackColor    =   Color.Gray;
            c               =   new TableCell();
            c.Text          =   "<strong>Total</strong>";
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   string.Format("<strong>{0}</strong>",totRecords);
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
            FillRow2(tb);
            tr              =   new TableRow();
            tr.BackColor    =   Color.Gray;
            c               =   new TableCell();
            c.ColumnSpan    =   4;
            fmt                 =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM7","(*) is for Check duplicates.<br />Date:  {0}{1}");
            c.Text          =   "<strong>"+string.Format(fmt,DateTime.Now,StStr.strBr)+"</strong>";
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
            RadTbSummary.Controls.Add(tb);
        }

        void Save()
        {
            string fileName             =   string.Format("Crm2Cm_{0}.html",DateTime.Now.ToLongDateString().Replace(' ','_').Replace('.','_').Replace(':','_'));
            string path                 =   System.IO.Path.Combine(DocumentsFolder,fileName);
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm Save BEG filename '{0}', path: {1}.", fileName, path), Crm2CrmTrace.Sw.Info);
            StringWriter sw			    =   null;
            try
            {
                int idx                 =   0;
                while (File.Exists(path))
                {
                    fileName            =   string.Format("Crm2Cm_{0}-{1}.txt",DateTime.Now.ToLongDateString().Replace(' ','_').Replace('.','_').Replace(':','_'),idx++);
                    path                =   System.IO.Path.Combine(DocumentsFolder,fileName);
                }
			    sw			            =   new StringWriter();
                HtmlTextWriter tw       =   new HtmlTextWriter(sw);
                RadTbSummary.RenderControl(tw);
                string content          =   sw.ToString();
                sw.Close();
                File.WriteAllText(path,content);
                Literal Saved           =   new Literal();
                string fmt              =   LocalizeHelper.Localize("CRM2CRM_SAVED","Saved in {0}.");
                Saved.Text              =   string.Format(fmt,path);
                RadTbSummary.Controls.Add(Saved);
            }
            catch (Exception ex)
            {
                if (Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm Save filename '{0}', ex: {1}.", fileName, ex), Crm2CrmTrace.Sw.Info);
                return;
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm Save END filename '{0}', path: {1}.", fileName, path), Crm2CrmTrace.Sw.Info);
        }

        void AddCell3(Table tb,string schemaName,string primKey)
        {
            TableRow tr         =   new TableRow();
            TableCell c         =   new TableCell();
            c.Text              =   schemaName;
            tr.Cells.Add(c);
            if ( DicOk.ContainsKey(schemaName) )
            {
                c               =   new TableCell();
                c.Text          =   DicOk[schemaName].Copied.ToString();
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   DicOk[schemaName].Errors.ToString();
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   DicOk[schemaName].Created.ToString();
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   DicOk[schemaName].Duplicates.ToString();
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   DicOk[schemaName].Updated.ToString();
                tr.Cells.Add(c);
            }
            else
            {
                c               =   new TableCell();
                c.Text          =   "0";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "0";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "0";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "0";
                tr.Cells.Add(c);
                c               =   new TableCell();
                c.Text          =   "0";
                tr.Cells.Add(c);
            }
            c                   =   new TableCell();
            c.Text              =   FetchCount(Wrapper,schemaName,primKey).ToString();
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
        }
        
        void ReportResult()
        {
            Table tb        =   new Table();
            tb.CellPadding  =   2;
            tb.CellSpacing  =   0;
            tb.BorderColor  =   Color.Black;
            tb.BorderWidth  =   new Unit(1);
            tb.GridLines    =   GridLines.Both;
            tb.HorizontalAlign  =    HorizontalAlign.Center;
            TableRow tr     =   new TableRow();
            tr.BackColor    =   Color.Gray;
            TableCell c     =   new TableCell();
            c.Text          =   "<strong>Entity</strong>";
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   "<strong>Copied</strong>";
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   "<strong>Errors</strong>";
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   "<strong>Created</strong>";
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   "<strong>Duplicates</strong>";
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   "<strong>Updated</strong>";
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
            c               =   new TableCell();
            c.Text          =   "<strong>Final Count</strong>";
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
            if (CbCustomers.Checked)
            {
                AddCell3(tb,CrmStr.account,CrmStr.accountid);
                AddCell3(tb,CrmStr.contact,CrmStr.contactid);
                AddCell3(tb,CrmStr.lead,CrmStr.leadid);
                AddCell3(tb,CrmStr.customeraddress,CrmStr.customeraddressid);
                AddCell3(tb,CrmStr.competitor,CrmStr.competitorid);
                AddCell3(tb,CrmStr.relationshiprole,CrmStr.relationshiproleid);
                AddCell3(tb,CrmStr.relationshiprolemap,CrmStr.relationshiprolemapid);
            }
            if (CbProducts.Checked)
            {
                AddCell3(tb,CrmStr.uom,CrmStr.uomid);
                AddCell3(tb,CrmStr.uomschedule,CrmStr.uomscheduleid);
                AddCell3(tb,CrmStr.discounttype,CrmStr.discounttypeid);
                AddCell3(tb,CrmStr.discount,CrmStr.discountid);
                AddCell3(tb,CrmStr.pricelevel,CrmStr.pricelevelid);
                AddCell3(tb,CrmStr.product,CrmStr.productid);
                AddCell3(tb,CrmStr.productpricelevel,CrmStr.productpricelevelid);
            }
            if (CbOpportunities.Checked)
            {
                AddCell3(tb,CrmStr.opportunity,CrmStr.opportunityid);
            }
            if (CbQuotes.Checked)
            {
                AddCell3(tb,CrmStr.quote,CrmStr.quoteid);
            }
            if (CbOrders.Checked)
            {
                AddCell3(tb,CrmStr.salesorder,CrmStr.salesorderid);
            }
            if (CbInvoices.Checked)
            {
                AddCell3(tb,CrmStr.invoice,CrmStr.invoiceid);
            }
            if (CbActivities.Checked)
            {
                AddCell3(tb,CrmStr.task,CrmStr.activityid);
                AddCell3(tb,CrmStr.phonecall,CrmStr.activityid);
                AddCell3(tb,CrmStr.appointment,CrmStr.activityid);
                AddCell3(tb,CrmStr.letter,CrmStr.activityid);
                AddCell3(tb,CrmStr.email,CrmStr.activityid);
                AddCell3(tb,CrmStr.annotation,CrmStr.annotationid);
            }
            if (CbLists.Checked)
            {
                AddCell3(tb,CrmStr.list,CrmStr.listid);
            }
            if (CbCampaigns.Checked)
            {
                AddCell3(tb,CrmStr.campaign,CrmStr.campaignid);
                AddCell3(tb,CrmStr.campaignactivity,CrmStr.activityid);
                AddCell3(tb,CrmStr.campaignresponse,CrmStr.activityid);
            }
            if ( CbContracts.Checked )
            {
                AddCell3(tb,CrmStr.contracttemplate,CrmStr.contracttemplateid);
                AddCell3(tb,CrmStr.contract,CrmStr.contractid);
                AddCell3(tb,CrmStr.contractdetail,CrmStr.contractdetailid);
            }
            if ( CbCalendar.Checked )
            {
                AddCell3(tb,CrmStr.calendar,CrmStr.calendarid);
                AddCell3(tb,CrmStr.annualfiscalcalendar,CrmStr.userfiscalcalendarid);
                AddCell3(tb,CrmStr.fixedmonthlyfiscalcalendar,CrmStr.userfiscalcalendarid);
                AddCell3(tb,CrmStr.monthlyfiscalcalendar,CrmStr.userfiscalcalendarid);
                AddCell3(tb,CrmStr.quarterlyfiscalcalendar,CrmStr.userfiscalcalendarid);
                AddCell3(tb,CrmStr.semiannualfiscalcalendar,CrmStr.userfiscalcalendarid);
            }
            if ( CbService.Checked )
            {
                AddCell3(tb,CrmStr.site,CrmStr.siteid);
                AddCell3(tb,CrmStr.resource,CrmStr.resourceid);
                AddCell3(tb,CrmStr.service,CrmStr.serviceid);
                AddCell3(tb,CrmStr.incident,CrmStr.incidentid);
                AddCell3(tb,CrmStr.serviceappointment,CrmStr.activityid);
            }
            string customLst        =   RadLbCustomEnt.SelectedValue;
            string[] Customs        =   customLst.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
            bool oddrw              =   false;
            foreach ( string custEnt in Customs )
            {
                DynEntity custDyn   =   new DynEntity(Wrapper2,custEnt);
                string primKey      =   custDyn.PrimaryKeyName; // heavy
                AddCell3(tb,custEnt,primKey);
                oddrw               =   !oddrw;
            }
            if ( oddrw )
                FillRow2(tb);
            tr              =   new TableRow();
            tr.BackColor    =   Color.Gray;
            c               =   new TableCell();
            c.Text          =   "<strong>Total</strong>";
            tr.Cells.Add(c);
            c               =   new TableCell();
            c.Text          =   string.Format("<strong>{0}</strong>",totRecords);
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
            FillRow2(tb);
            tr              =   new TableRow();
            tr.BackColor    =   Color.Gray;
            c               =   new TableCell();
            c.ColumnSpan    =   4;
            string fmt      =   LocalizeHelper.Localize("CRM2CRM_ACTIONSUM7","(*) is for Check duplicates.<br />Date:  {0}{1}");
            c.Text          =   "<strong>"+string.Format(fmt,DateTime.Now,StStr.strBr)+"</strong>";
            tr.Cells.Add(c);
            tb.Rows.Add(tr);
            RadTbSummary.Controls.Add(tb);
            if (Settings[ST2C.SaveExecSummary].ToBool() )
                Save();
        }

        void FillTbWithUsers(DataTable Tb)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Crm2Crm FillTbWithUsers BEG.",Crm2CrmTrace.Sw.Info);
            // Read all target crm users and store them in target userList
            GenericDynQueryMultiple<ADNDynSystemUser> allUsersQuery =   new GenericDynQueryMultiple<ADNDynSystemUser>(Wrapper,ResetWrapper,CrmStr.systemuser);
            InternalBusinessEntityCollection allUsers               =   allUsersQuery.adminRetrieve();
            EntityConfig TConfigSysUser                             =   new EntityConfig(Wrapper,CrmStr.systemuser);
            PropertyDescriptorCollection _columnDescriptors         =   null;
            Wrapper.Util.ExecForEachDynamicEntity(allUsers,
                delegate(InternalDynamicEntity de)
                {
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers loop for destusers InternalDynamicEntity: [{0}]", de),Crm2CrmTrace.Sw.Info);
                    ADNDynSystemUser ob                             =   new ADNDynSystemUser(Wrapper, de, _columnDescriptors,null);
                    ob.EntityMData                                  =   TConfigSysUser.entityMetaData;
                    _columnDescriptors                              =   ob.PropertyDescriptorCollection;
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers loop lastname: {0},systemuserid: {1}, domainname: [{2}]",ob.lastname,ob.systemuserid, ob.domainname),Crm2CrmTrace.Sw.Info);
                    if ( ob.domainname.Trim() == string.Empty )
                        return true;
                    TargetUsers.Add(ob.domainname,ob);
                    TargetUsers2.Add(ob.systemuserid,ob);
                    // Trap current Wrapper admin and take it as Default user for mapping
                    bool isDefaultTargetUser                        =   (ob.systemuserid == Wrapper.adminUserId);
                    if ( isDefaultTargetUser )
                        DefaultTargetUser                           =   ob;
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers adding to TargetUsers: [{0}], isDefaultTargetUser: {1}", ob.domainname,isDefaultTargetUser),Crm2CrmTrace.Sw.Info);
                    return true;
                });
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Crm2Crm FillTbWithUsers before reading source users.",Crm2CrmTrace.Sw.Info);
            // Read all source crm users and try to map them to some target user using domainName
            allUsersQuery                                           =   new GenericDynQueryMultiple<ADNDynSystemUser>(Wrapper2,ResetWrapper,CrmStr.systemuser);
            allUsers                                                =   allUsersQuery.adminRetrieve();
            TConfigSysUser                                          =   new EntityConfig(Wrapper2,CrmStr.systemuser);
            _columnDescriptors                                      =   null;
            Wrapper2.Util.ExecForEachDynamicEntity(allUsers,
                delegate(InternalDynamicEntity de)
                {
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers loop for source InternalDynamicEntity: [{0}]", de),Crm2CrmTrace.Sw.Info);
                    ADNDynSystemUser ob                             =   new ADNDynSystemUser(Wrapper2, de, _columnDescriptors,null);
                    ob.EntityMData                                  =   TConfigSysUser.entityMetaData;
                    _columnDescriptors                              =   ob.PropertyDescriptorCollection;
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers loop2 lastname: {0},systemuserid: {1}, domainname: [{2}]",ob.lastname,ob.systemuserid, ob.domainname),Crm2CrmTrace.Sw.Info);
                    if ( ob.domainname.Trim() == string.Empty )
                        return true;
                    DataRow rw                                      =   Tb.NewRow();
                    rw[strSourceUserId]                             =   ob.systemuserid;
                    rw["LastName"]                                  =   ob.lastname;
                    rw[strSourceDomainName]                         =   ob.domainname;
                    // now try to find it in our TargetUsers col
                    ADNDynSystemUser sysuser                        =   null;
                    if ( TargetUsers.ContainsKey(ob.domainname) )
                        sysuser                                     =   TargetUsers[ob.domainname];
                    bool isUserExisting                             =   (sysuser != null);
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers Identical user found by domainName: {0}.",isUserExisting),Crm2CrmTrace.Sw.Info);
                    if ( isUserExisting )
                    {
                        rw[strTargetDomainName]                     =   sysuser.systemuserid;
                        // take here the opportunity to fill our association list
                        // no too early ->make it after user change tab DicDic[CrmStr.systemuser].Add(ob.systemuserid,sysuser);
                    }
                    else
                    {
                        ADNDynSystemUser defuser                    =   DefaultTargetUser;
                        bool isdefaultUserNull                      =   ( defuser == null);
                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers defaultUser null: {0}.",isdefaultUserNull),Crm2CrmTrace.Sw.Info);
                        if ( isdefaultUserNull && TargetUsers.Count > 0 )
                            defuser                                 =   TargetUsers[TargetUsers.Keys[0]];
                        isdefaultUserNull                           =   ( defuser == null);
                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers defuser null: {0}.",isdefaultUserNull),Crm2CrmTrace.Sw.Info);
                        if ( !isdefaultUserNull)
                        {
                            rw[strTargetDomainName]                 =   defuser.systemuserid;
                        }
                        else
                        {
                            rw[strTargetDomainName]                 =   Guid.Empty;
                        }
                    }
                    if (Crm2CrmTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers TargetDomainName: {0}",rw[strTargetDomainName]),Crm2CrmTrace.Sw.Info);
                    Tb.Rows.Add(rw);
                    if ( Crm2CrmTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers after Ctor for objectname: [{0}] of type: {1}", ob.SchemaName, ob),Crm2CrmTrace.Sw.Info);
                    return true;
                }
                );
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm FillTbWithUsers GET END Count: {0}",Tb.Rows.Count),Crm2CrmTrace.Sw.Info);
        }

        DataTable TbUserMappings
        {
            get
            {
                object obj              =   Session[strMappingData];
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm TbUserMappings GET BEG obj != null: {0}",obj != null),Crm2CrmTrace.Sw.Info);
                if (obj != null)
                {
                    return (DataTable)obj;
                }
                DataTable Tb            =   new DataTable("Mappings");
                DataColumn c            =   Tb.Columns.Add(strSourceUserId, typeof(Guid));
                Tb.Columns.Add("LastName", typeof(string));
                Tb.Columns.Add(strSourceDomainName, typeof(string));
                Tb.Columns.Add(strTargetDomainName, typeof(Guid));
                Tb.PrimaryKey           =   new DataColumn[] { c };
                FillTbWithUsers(Tb);
                Session[strMappingData] =   Tb;
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm TbUserMappings GET END Count: {0}",Tb.Rows.Count),Crm2CrmTrace.Sw.Info);
                return Tb;
            }
        }

        ADNDynSystemUser DefaultTargetUser
        {
            get
            {
                object obj          =   Session["DefaultTargetUser"];
                if (obj != null)
                    return (ADNDynSystemUser)obj;
                return null;
            }
            set
            {
                Session["DefaultTargetUser"]  =   value;
            }
        }

        SortedList<string,ADNDynSystemUser> TargetUsers
        {
            get
            {
                object obj                  =   Session["TargetUsers"];
                if (obj == null)
                {
                    obj                     =   new SortedList<string,ADNDynSystemUser>();
                    Session["TargetUsers"]  =   obj;
                }
                return (SortedList<string,ADNDynSystemUser> )obj;
            }
            set
            {
                Session["TargetUsers"]      =   value;
            }
        }

        SortedList<Guid,ADNDynSystemUser> TargetUsers2
        {
            get
            {
                object obj                  =   Session["TargetUsers2"];
                if (obj == null)
                {
                    obj                     =   new SortedList<Guid,ADNDynSystemUser>();
                    Session["TargetUsers2"] =   obj;
                }
                return (SortedList<Guid,ADNDynSystemUser> )obj;
            }
            set
            {
                Session["TargetUsers2"]     =   value;
            }
        }

        DataTable TbTargetDomainName
        {
            get
            {
                object obj                  =   Session[strTargetDomainName];
                if (obj != null)
                {
                    return (DataTable)obj;
                }
                DataTable Tb                =   new DataTable("TargetUsers");
                DataColumn c                =   Tb.Columns.Add("DestId", typeof(Guid));
                Tb.Columns.Add(strTargetDomainName, typeof(string));
                Tb.PrimaryKey               =   new DataColumn[] { c };
                for (int i = 0; i < TargetUsers.Count; i++)
                {
                    ADNDynSystemUser sysuser=  TargetUsers.Values[i];
                    DataRow rw              =   Tb.NewRow();
                    rw["DestId"]            =   sysuser.systemuserid;
                    rw[strTargetDomainName] =   sysuser.domainname;
                    Tb.Rows.Add(rw);
                }
                Session[strTargetDomainName]=   Tb;
                return Tb;
            }
        }

        /// <summary>
        /// Get the common custom entities list
        /// </summary>
        List<CrmEntityListItem> GetCutomEntities()
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm GetCutomEntities  BEG.",Crm2CrmTrace.Sw.Info);
            SortedList<string,CrmEntityListItem> lst2   =   MetadataCache.GetCustomEntities(Wrapper2);
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm GetCutomEntities lst2.Count: {0}.",lst2.Count),Crm2CrmTrace.Sw.Info);
            SortedList<string,CrmEntityListItem> lst    =   MetadataCache.GetCustomEntities(Wrapper);
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm GetCutomEntities lst.Count: {0}.",lst.Count),Crm2CrmTrace.Sw.Info);
            List<CrmEntityListItem> custLst             =   new List<CrmEntityListItem>();
            foreach ( string schemaNm in lst2.Keys )
            {
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm GetCutomEntities found schemaNm: {0}.",schemaNm),Crm2CrmTrace.Sw.Info);
                if ( !lst.ContainsKey(schemaNm) )
                    continue;
                string displayName  =   lst2[schemaNm].displayName;
                custLst.Add(lst2[schemaNm]);
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm GetCutomEntities added schemaNm: {0}.",schemaNm),Crm2CrmTrace.Sw.Info);
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm GetCutomEntities END count: {0}.",custLst.Count),Crm2CrmTrace.Sw.Info);
            return custLst;
        }

        /// <summary>
        /// Create the userMapping dic
        /// </summary>
        void ReadMappings()
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm ReadMappings BEG.",Crm2CrmTrace.Sw.Info);
            DataTable tb                =   TbUserMappings;
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ReadMappings tb.Rows.Count: {0}.",tb.Rows.Count),Crm2CrmTrace.Sw.Info);
            DicDynEnt Dic               =   new DicDynEnt();
            DicDic[CrmStr.systemuser]   =   Dic;
            for(int i=0 ; i < tb.Rows.Count ; i++ )
            {
                DataRow rw              =   tb.Rows[i];
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm ReadMappings i: {0}, SourceUserId: {1}, TargetDomainName: {2}",i,rw[strSourceUserId],rw[strTargetDomainName]),Crm2CrmTrace.Sw.Info);
                Dic.Add((Guid)rw[strSourceUserId],TargetUsers2[(Guid)rw[strTargetDomainName]]);
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Crm2Crm ReadMappings END.",Crm2CrmTrace.Sw.Info);
        }

        #region Users Grid Management

//        bool _isBound = false;
        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            bool isGridDataItem     =   e.Item is GridDataItem;
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadGrid1_ItemCreated BEG isGridDataItem: {0}",isGridDataItem),Crm2CrmTrace.Sw.Info);
            if (isGridDataItem)
            {
                if (Crm2CrmTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadGrid1_ItemCreated Item Type: {0}",((GridDataItem)e.Item).ItemType),Crm2CrmTrace.Sw.Info);
                GridColumn cl       =   RadGrid1.MasterTableView.GetColumnSafe(strTargetDomainName);
                if (cl != null)
                {
                    (((GridDropDownColumnEditor)((GridDropDownColumn)cl).ColumnEditor)).DataSource   = TbTargetDomainName;
//                    _isBound = true;
                }
            }
        }
        
        private void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadGrid1_NeedDataSource BEG RebindReason: {0}, RadTabStrip1.SelectedIndex: {1}",e.RebindReason,RadTabStrip1.SelectedIndex),Crm2CrmTrace.Sw.Info);
            if ( ( RadTabStrip1.SelectedIndex < 4 ) && ( e.RebindReason != GridRebindReason.ExplicitRebind ))
                    RadGrid1.DataSource     =   null;
            else    RadGrid1.DataSource     =   TbUserMappings;
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Crm2Crm RadGrid1_NeedDataSource END.",Crm2CrmTrace.Sw.Info);
        }

        protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadGrid1_UpdateCommand BEG e.Item : {0}",e.Item),Crm2CrmTrace.Sw.Info);
            GridEditableItem editedItem     =   e.Item as GridEditableItem;
            DataTable uTable                =   TbUserMappings;
            string strReq                   =   string.Format("SourceUserId = '{0}'",editedItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex][strSourceUserId]);
            //Locate the changed row in the DataSource
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadGrid1_UpdateCommand Request: {0}",strReq),Crm2CrmTrace.Sw.Info);

            DataRow[] changedRows           =   uTable.Select(strReq);
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadGrid1_UpdateCommand changedRows.Length: {0}",changedRows.Length),Crm2CrmTrace.Sw.Info);

            if (changedRows.Length != 1)
            {
                RadGrid1.Controls.Add(new LiteralControl("Error changed value not found, retry."));
                e.Canceled                  =   true;
                return;
            }

            //Update new values
            Hashtable newValues         =   new Hashtable();
            //The GridTableView will fill the values from all editable columns in the hash
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

            DataRow changedRow          =   changedRows[0];
            changedRow.BeginEdit();
            try
            {
                foreach (DictionaryEntry entry in newValues)
                {
                    object ob           =   entry.Value;
                    if (ob != null)
                    {
                        changedRow[(string)entry.Key] = entry.Value;
                        if (Crm2CrmTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadGrid1_UpdateCommand updating field: {0}, Value: {1}", entry.Key, entry.Value), Crm2CrmTrace.Sw.Info);
                    }
                }
                changedRow.EndEdit();
            }
            catch (Exception ex)
            {
                if (Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm RadGrid1_UpdateCommand ex: {0}",ex),Crm2CrmTrace.Sw.Info);
                changedRow.CancelEdit();
                RadGrid1.Controls.Add(new LiteralControl("Unable to update Orders. Reason: " + ex.Message));
                e.Canceled                  =   true;
            }

            uTable.AcceptChanges();

            string msg  =   string.Format("User mapping {0} updated",changedRow[strSourceUserId]);
            RadGrid1.Controls.Add(new LiteralControl(msg));
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Crm2Crm RadGrid1_UpdateCommand END "+msg,Crm2CrmTrace.Sw.Info);
        }

        void RadGrid1_ItemDataBound(object sender,GridItemEventArgs e)
        {
            if (e.Item is GridEditableItem )
            {
                GridEditableItem itm    =   e.Item as GridEditableItem;
             if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadGrid1_ItemDataBound BEG Item: {0}, Type: {1}, IsInEditMode: {2}, Display: {3}",
                        new object[]{itm[strSourceDomainName].Text,e.Item.ItemType,e.Item.IsInEditMode,e.Item.Display}),Crm2CrmTrace.Sw.Info);
           }
        }
 
        #endregion Users Grid Management

        #region duplicates management


        /// <summary>
        /// Enable disable the startdate input
        /// </summary>
        void CbCopyAll_CheckedChanged(object sender,EventArgs e)
        {
            RadStartDate.Enabled            =   !CbCopyAll.Checked;
        }
        
        /// <summary>
        /// When checked for duplicate for all items
        /// </summary>
        void cbCheckDuplicates_CheckedChanged(object sender,EventArgs e)
        {
            bool checkStatus                =   cbCheckDuplicates.Checked;
            CbCustomersDups.Checked         =   checkStatus;
            CbCustomerRelationsDups.Checked =   checkStatus;
            CbProductsDups.Checked          =   checkStatus;
            CbOpportunitiesDups.Checked     =   checkStatus;
            CbQuotesDups.Checked            =   checkStatus;
            CbOrdersDups.Checked            =   checkStatus;
            CbInvoicesDups.Checked          =   checkStatus;
            CbActivitiesDups.Checked        =   checkStatus;
            CbListsDups.Checked             =   checkStatus;
            CbCampaignsDups.Checked         =   checkStatus;
            CbContractsDups.Checked         =   checkStatus;
            CbServiceDups.Checked           =   checkStatus;
            // When check global is presses disable individual buttons
            CbCustomersDups.Enabled         =   !checkStatus;
            CbCustomerRelationsDups.Enabled =   !checkStatus;
            CbProductsDups.Enabled          =   !checkStatus;
            CbOpportunitiesDups.Enabled     =   !checkStatus;
            CbQuotesDups.Enabled            =   !checkStatus;
            CbOrdersDups.Enabled            =   !checkStatus;
            CbInvoicesDups.Enabled          =   !checkStatus;
            CbActivitiesDups.Enabled        =   !checkStatus;
            CbListsDups.Enabled             =   !checkStatus;
            CbCampaignsDups.Enabled         =   !checkStatus;
            CbContractsDups.Enabled         =   !checkStatus;
            CbServiceDups.Enabled           =   !checkStatus;
        }

        #endregion duplicates management

        #region TabStrip Management

        void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadTabStrip1_TabClick  BEG TabIndex: {0}.",e.Tab.TabIndex),Crm2CrmTrace.Sw.Info);
            int nextidx                 =   e.Tab.TabIndex;
            int idx                     =   RadTabStrip1.SelectedIndex;
            // Hide update button when going backward
            if ( idx < RadTabStrip1.Tabs.Count -1)
                updateBtn.Visible       =   false;
            // When going back in tabs, we force usage of button to go up again to respect init methods
            while ( nextidx < idx )
            {
                RadTab Tab              =   RadTabStrip1.Tabs[idx];
                Tab.Enabled             =   false;
                idx--;
            }
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm RadTabStrip1_TabClick  END updateBtn.Visible: {0}.",updateBtn.Visible),Crm2CrmTrace.Sw.Info);
        }

        /// <summary>
        /// According the radio button selected, enable the correspnding panel
        /// </summary>
        void SetCRMVersion()
        {
            if ( RdBtnCRMV3.Checked )
            {
                panelCRM4.Visible   =   false;
                panelCRM3.Visible   =   true;
            }
            else
            {
                panelCRM4.Visible   =   true;
                panelCRM3.Visible   =   false;
            }
        }

        bool CheckServer()
        {
            try
            {
                CRMWrapperBase w    =   Wrapper2;
            }
            catch ( Exception ex )
            {
                if (Crm2CrmTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Crm2Crm CheckServer ex: {0}.",ex),Crm2CrmTrace.Sw.Info);
                return false;
            }
            return true;
        }

        void CustomValidConnect_ServerValidate(object source,ServerValidateEventArgs args)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CustomValidConnect_ServerValidate  BEG args.Value: {0}.",args.Value),Crm2CrmTrace.Sw.Info);
            // Save Pwd in Session
            Session["Pwd"]          =   RadTbPwd1.Text;
            args.IsValid            =   CheckServer();
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm CustomValidConnect_ServerValidate END IsValid: {0}.",args.IsValid),Crm2CrmTrace.Sw.Info);
        }

        void BtnNext_Click(object sender, ImageClickEventArgs e)
        {
            int idx                         =   RadTabStrip1.SelectedIndex;
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm BtnNext_Click  BEG TabIndex: {0}.",idx),Crm2CrmTrace.Sw.Info);
			RadTab Tab                      =   RadTabStrip1.Tabs[idx+1];
            RadPageView PageView            =   RadMultiPage1.PageViews[idx+1];
            bool ok                         =   true;
            switch (Tab.Index)
            {
                case 1:
                    SetCRMVersion();
                    break;
                case 2:
                    ok                      =   Page.IsValid;
                    if ( ok )
                    {
                        RadLbCustomEnt.DataSource       =   GetCutomEntities();
                        RadLbCustomEnt.DataValueField   =   "entityName";
                        RadLbCustomEnt.DataTextField    =   "displayName";
                        RadLbCustomEnt.DataBind();
                    }
                    break;
                case 4:
                    //ReadEntities();
                    RadGrid1.DataSource     =   null;
                    RadGrid1.Rebind();
                    break;
                case 5:
                    ReadCounts();
                    break;
                case 6:
                    ReadData();
                    // allow update or reset
                    LabelSummary.Text       =   LocalizeHelper.Localize("CRM2CRM_LASTSUMMARY","Process summary");
                    resetBtn.Visible        =   true;
                    updateBtn.Visible       =   true;
                    break;
            }
            if ( ok )
            {
		        Tab.Enabled                 =   true;
		        Tab.Selected                =   true;
                PageView.Selected           =   true;
            }

            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Crm2Crm BtnNext_Click  END Tab.Index: {0}, ok: {1}, updateBtn.Visible: {2}.",Tab.Index,ok,updateBtn.Visible),Crm2CrmTrace.Sw.Info);
		}

        /// <summary>
        /// reset everything and go to first tab
        /// </summary>
        void resetBtn_Click(object sender,ImageClickEventArgs e)
        {
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Crm2Crm resetBtn_Click  BEG.",Crm2CrmTrace.Sw.Info);
            updateBtn.Visible           =   false;
            resetBtn.Visible            =   false;
            // When going back in tabs, we force usage of button to go up again to respect init methods
            for( int idx = 1 ; idx < RadTabStrip1.Tabs.Count ; idx++ )
            {
                RadTab Tab              =   RadTabStrip1.Tabs[idx];
                Tab.Enabled             =   false;
            }
            RadTabStrip1.SelectedIndex  =   0;
            RadMultiPage1.SelectedIndex =   0;
            InitData();
            if (Crm2CrmTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Crm2Crm resetBtn_Click  END.",Crm2CrmTrace.Sw.Info);
        }

        #endregion TabStrip Management
        
        #region Std Control override

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            resetBtn.SkinID     =   "Reset_" + strcult;
            updateBtn.SkinID    =   "Update_" + strcult;
            BtnNext0.SkinID     =   "setupnext_" + strcult;
            BtnNext.SkinID      =   "setupnext_" + strcult;
            BtnNext1.SkinID     =   "setupnext_" + strcult;
            BtnNext2.SkinID     =   "setupnext_" + strcult;
            BtnNext3.SkinID     =   "setupnext_" + strcult;
            BtnNext4.SkinID     =   "setupnext_" + strcult;
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
        

        private void InitializeComponent()
        {
            Load                                +=  new EventHandler(Page_Load);
            ADNUpdateModule                     +=  new PortalModuleEventHandler(Crm2Crm_ADNUpdateModule);
            resetBtn.Click                      +=  new ImageClickEventHandler(resetBtn_Click);
            RadGrid1.NeedDataSource             +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.UpdateCommand              +=  new GridCommandEventHandler(RadGrid1_UpdateCommand);
            RadGrid1.ItemCreated                +=  new GridItemEventHandler(RadGrid1_ItemCreated);
            RadTabStrip1.TabClick               +=  new RadTabStripEventHandler(RadTabStrip1_TabClick);
            BtnNext0.Click                      +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext.Click                       +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext1.Click                      +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext2.Click                      +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext3.Click                      +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext4.Click                      +=  new ImageClickEventHandler(BtnNext_Click);
            CbCopyAll.AutoPostBack              =   true;
            CbCopyAll.CheckedChanged            +=  new EventHandler(CbCopyAll_CheckedChanged);
            cbCheckDuplicates.AutoPostBack      =   true;
            cbCheckDuplicates.CheckedChanged    +=  new EventHandler(cbCheckDuplicates_CheckedChanged);
            CustomValidConnect.ServerValidate   +=  new ServerValidateEventHandler(CustomValidConnect_ServerValidate);
      }

        #endregion Std Control override
    }
}